在比较嵌套类属性(Compare attribute in nested class)

2019-10-19 13:41发布

我想重用我的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有物业UserConfirmEmailConfirmPassword性能。

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

当我tryed [Compare("Password")]的错误是:

该物业UserViewModel.Password找不到。

并与[Compare("User.Password")]的错误是:

该物业UserViewModel.User.Password找不到。

有没有办法做到这一点?

编辑:解决方案:

我tryed againd的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.Emailmodel => 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>

现在,两个客户端和服务器端进行验证。

Answer 1:

也许重复: MVC3比较属性和嵌套的对象属性

一种解决方法可能是平坦的属性到您的视图模型,如:

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

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


文章来源: Compare attribute in nested class