MVC3比较属性和嵌套的对象属性 [英] MVC3 Compare attribute and nested object properties

查看:145
本文介绍了MVC3比较属性和嵌套的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

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.

这篇关于MVC3比较属性和嵌套的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆