我想在我的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
以及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>
现在验证了客户端和服务器端。
答案 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; }
}