MVC 3中整个无阻碍客户端验证都依赖于模型,我不想在我的模型上添加ConfirmPassword属性,该怎么办?
我完全同意您的看法。这就是为什么你应该使用视图模型。然后在你的视图模型(一个专门设计给定视图要求的类)上,你可以使用[Compare]
属性:
public class RegisterViewModel
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Confirm password doesn't match, Type again !")]
public string ConfirmPassword { get; set; }
}
然后让您的控制器操作采用此视图模型。
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: Map the view model to a domain model and pass to a repository
// Personally I use and like AutoMapper very much (http://automapper.codeplex.com)
return RedirectToAction("Success");
}
[Compare(nameof(Password), ...]
而不是硬编码Password
属性名称。 - Mariusz Jamro看一下MVC3应用程序的默认VS2010模板。
它包含一个名为RegisterModel(一个“视图模型”)的模型,其中包含密码和确认密码属性。验证设置在确认密码上。
因此,答案是MVC中的模型不必(通常不是)与您的业务模型相同。