MVC3 Compare Attribute and Properties of Nested Objects

I have the following:

public class Address 
{
    public string Email { get; set; }
}

public class CheckoutViewModel 
{
    public Address Address { get; set; }

    [Compare("Address.Email", ErrorMessage = "The email addresses you entered do not match")]
    public string ConfirmEmailAddress { get; set; }
}

      

With client-side JS, this works and is validated correctly. However, when tested without Javascript enabled, the form returns, but the ModelState error states:

Could not find a property named Address.Email.

Any ideas as to why this works on the client but not the server? What is the solution in this case?

Many thanks.

+3


source to share


1 answer


If you browse the generated HTML source, you should find that the email input element is named "Address.Email" and therefore the validation works on the client side.

However, it looks like the attribute is not built to handle nested properties, so it does not work at the server level (since there is no property called "Address.Email"). As a result, you will need to ensure that both properties are at the same level (either in the ViewModel or in the Address class).



Your best bet, if possible, is to put the email address property in the view model and then populate the Address object later.

+2


source







All Articles