【发布时间】:2014-03-13 21:58:20
【问题描述】:
我想在我的UserViewModel 中重用我的User 类,因为它太大了,属性太多。
public class User
{
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
/* ... many other properties */
}
我的UserViewModel 拥有User 属性以及ConfirmEmail 和ConfirmPassword 属性。
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>
现在客户端和服务器端都被验证了。
【问题讨论】:
标签: c# asp.net-mvc-5 data-annotations