harman_kardon
harman_kardon

Reputation: 1717

MVC3 Compare attribute and nested object properties

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 a treat and validates properly. However, when testing without Javascript enabled, The form posts back but the ModelState error reads:

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.

Upvotes: 3

Views: 848

Answers (1)

Andy
Andy

Reputation: 561

If you view the HTML source generated you should find that the input element for Email is called "Address.Email", and this is why the validation works on the client side.

However it looks like the attribute is not built to handle nested properties and so at the server level it is not working (as there is no property called "Address.Email"). As a result you will need to make sure both properties are at the same level (either both on the ViewModel or both on the Address class).

Your best option if probably to put the Email address property onto the view model and then populate the Address object later.

Upvotes: 2

Related Questions