比较嵌套类中的属性 [英] Compare attribute in nested class

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

问题描述

我想在UserViewModel中重用我的User类,因为它太大,具有太多的属性.

I want to reuse my User class in my UserViewModel because it is too big, with too many properties.

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

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

    /* ... many other properties */
}

我的UserViewModel具有属性UserConfirmEmailConfirmPassword属性.

My UserViewModel have the property User and the ConfirmEmail and ConfirmPassword properties.

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.

The property UserViewModel.Password could not be found.

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

找不到属性UserViewModel.User.Password.

The property UserViewModel.User.Password could not be found.

没有办法做到吗?

解决方案:

我再次尝试了 thepirat000 答案,但是做了一些更改:

I tryed againd the thepirat000 answer, but with some changes:

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

User/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>

现在,客户端和服务器端均已通过验证.

Now the both client side and server side are validated.

推荐答案

也许是重复的:一种解决方法是将属性平放在视图模型中,例如:

A workaround could be to flat the properties into your view model, like:

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

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

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

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