MVC3 Compare attribute and nested object properties

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 10:22:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9784610/mvc3-compare-attribute-and-nested-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!