2

我有一个简单定义如下的地址对象:

public class Address
{
    public string StreetNumber { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
}

相当简单。根据我提出的另一个问题的答案的建议,当我将我的 UI 数据绑定到 Person 类型的对象(其中包含 Address MailingAddress 字段)时,我指的是这篇博文。

问题是 IDataError 接口方法没有验证 Address 类型的任何属性。

public string this[string columnName]
{
    get
    {
        string result = null;

        // the following works fine
        if(columnName == "FirstName")
        {
            if (string.IsNullOrEmpty(this.FirstName))
                result = "First name cannot be blank.";
        }
        // the following does not run 
        // mostly because I don't know what the columnName should be
        else if (columnName == "NotSureWhatToPutHere")
        {
            if (!Util.IsValidPostalCode(this.MailingAddress.PostalCode))
                result = "Postal code is not in a know format.";
        }
        return result;
    }
}

所以,显然我不知道 columnName 将是什么......我已经完成了它,除了任何公共属性(内在类型)之外,它从来没有其他任何东西。我什至尝试过运行和打破如下声明:

if (columnName.Contains("Mailing") || columnName.Contains("Postal"))
    System.Windows.Forms.MessageBox.Show(columnName);

一切都无济于事。

有什么我想念的吗?

4

2 回答 2

3

您需要在要为其提供错误消息的所有类上定义 IErrorInfo。

于 2009-09-23T01:29:45.517 回答
0

看看我的回答here

这解释了如何使用模型绑定器来添加模型的“类级别”检查,而不必使用IDataError- 正如您在此处看到的那样,这可能非常笨拙。它仍然允许您使用 [Required] 属性或您拥有的任何其他自定义验证属性,但允许您添加或删除单个模型错误。有关如何使用数据注释的更多信息,我强烈推荐Scott Gu 的这篇文章

于 2010-01-17T12:57:25.750 回答