比较嵌套类中的属性

时间:2014-03-13 21:58:20

标签: c# asp.net-mvc-5 data-annotations

我想在我的User中重用我的UserViewModel类,因为它太大了,属性太多了。

public class User
{
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [DataType(DataType.Password)]
    public string Password { get; set; }

    /* ... many other properties */
}

我的UserViewModel拥有属性User以及ConfirmEmailConfirmPassword属性。

public class UserViewModel 
{
    public User User;

    [DataType(DataType.EmailAddress)]
    [Compare("User.Email")]
    public string ConfirmEmail { get; set; }

    [DataType(DataType.Password)]
    [Compare("User.Password")]
    public string ConfirmPassword { get; set; }
}

当我尝试[Compare("Password")]时,错误是:

  

找不到属性UserViewModel.Password。

对于[Compare("User.Password")],错误是:

  

找不到属性UserViewModel.User.Password。

没有办法做到这一点?

编辑:解决方案:

我再次尝试thepirat000答案,但有一些变化:

UserViewModel.cs

public class UserViewModel 
{
    public User User;

    public string UserEmail 
    { 
        get { return User.Email; } 
        set { User.Email = value; } 
    }

    [DataType(DataType.EmailAddress)]
    [Compare("UserEmail")]
    public string ConfirmEmail { get; set; }
}

用户/ Create.cshtml

在我看来,而不是:

<div class="form-group">
    @Html.LabelFor(model => model.User.Email)
    @Html.EditorFor(model => model.User.Email)
</div>
<div class="form-group">
    @Html.ValidationMessageFor(model => model.User.Email)
</div>

<div class="form-group pad-top">
    @Html.LabelFor(model => model.ConfirmEmail)
    @Html.EditorFor(model => model.ConfirmEmail)
    @Html.ValidationMessageFor(model => model.ConfirmEmail)
</div>

我将model => model.User.Email更改为model => model.UserEmail

<div class="form-group">
    @Html.LabelFor(model => model.UserEmail)
    @Html.EditorFor(model => model.UserEmail)
</div>
<div class="form-group">
    @Html.ValidationMessageFor(model => model.UserEmail)
</div>

<div class="form-group pad-top">
    @Html.LabelFor(model => model.ConfirmEmail)
    @Html.EditorFor(model => model.ConfirmEmail)
    @Html.ValidationMessageFor(model => model.ConfirmEmail)
</div>

现在验证了客户端和服务器端。

1 个答案:

答案 0 :(得分:1)

可能重复:MVC3 Compare attribute and nested object properties

解决方法可能是将属性展平到视图模型中,例如:

public class UserViewModel 
{
    public User User;
    public string UserEmail { get { return User.Email; } }

    [DataType(DataType.EmailAddress)]
    [Compare("UserEmail")]
    public string ConfirmEmail { get; set; }
}