MVC3比较属性和嵌套的对象属性属性、嵌套、对象

2023-09-03 17:50:44 作者:把心熬成铁

我有以下几点:

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; }
}

使用客户端的JS,这个工程一种享受,并验证正确。然而,测试没有使用Javascript功能时,该表单发送回不过的ModelState错误如下:

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:

找不到一个名为Address.Email属性。

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?

非常感谢。

推荐答案

如果您查看生成的HTML源代码,你应该发现,对于电子邮件input元素被称为Address.Email,这就是为什么验证工作的客户端。

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.

不过,它看起来像属性不能处理嵌套的属性,因此在服务器级别它不工作(因为没有所谓的Address.Email属性)。因此,您将需要确保这两个属性都在同一水平(或者都在视图模型或两个地址类)。

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.