我的问题与此问题类似,但我仍然在服务器端和客户端的验证方面遇到问题。我想对设置在不同模型中的两个属性进行比较。
我的模型如下:
public class User{
public string Password { get; set; }
}
public class UserRegisterViewModel {
public User User{ get; set; }
//This is suggested in linked question - as Compare can only work with local property
public string Password
{
get{return this.User.Password;}
}
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords must match")]
[Required(ErrorMessage = "Confirm password is required")]
[DisplayName("Confirm Password")]
public string CPassword { get; set; }
}
我的控制器动作是:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(UserRegisterViewModel model)
{
if (ModelState.IsValid) //This conditions is false
{
}
return View();
}
它重定向到再次注册页面,并显示验证错误Password must match
。有人可以帮忙吗?我已经检查了这个问题,它有点帮助,但并不完全。
如果我像下面这样更改模型结构,则会收到一条错误消息Could not find a property named User.Password
:
public class UserRegisterViewModel {
public User User{ get; set; }
[DataType(DataType.Password)]
[Compare("User.Password", ErrorMessage = "Passwords must match")]
[Required(ErrorMessage = "Confirm password is required")]
[DisplayName("Confirm Password")]
public string CPassword { get; set; }
}
编辑
我的 cshtml 页面代码如下所示。
<p>
@Html.LabelFor(model => model.User.Password)
@Html.PasswordFor(model => model.User.Password, new { @class = "wd189 inputtext" })
@Html.ValidationMessageFor(model => model.User.Password)
</p>
<p>
@Html.LabelFor(model => model.CPassword)
@Html.PasswordFor(model => model.CPassword, new { @class = "wd189 inputtext" })
@Html.ValidationMessageFor(model => model.CPassword)
</p>