IDataErrorInfo with complex types

I have an Address object that is defined simply like this:

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

      

Pretty simple. In response to another question I asked, I mean this blog post when binding my UI to an object of type Person (which contains an Address AddressingAddress field).

The problem is that the IDataError interface method does not validate any properties of type 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;
    }
}

      

So obviously I don't know what will happen with the columnName ... I went through it and it was never anything other than any public properties (built-in types). I even tried to run and hack an expression like:

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

      

All to no avail.

Is there something I am missing?

+2


source to share


2 answers


You need to define IErrorInfo for all classes for which you want to send error messages.



+3


source


Check out my answer here .



This explains how to use modelbinder to add class-level validation to your model without using it IDataError

- which, as you've seen here, can be quite clunky. It still allows the [Required] attributes or whatever custom validation attributes you have, but allows you to add or remove individual model errors. For more details on how to use data annotations, I highly recommend this post from Scott Gu .

0


source







All Articles