如何在 MVC 3 ASP.NET 正确实现"Confirm Password"?



已经有一个关于同一主题的回答问题,但由于它是2009年的,我认为它已经过时了。

如何在ASP中正确实现"确认密码"。Net MVC 3?

我在网上看到了很多选项,其中大多数使用模型中的CompareAttribute,就像这个

问题是ConfirmPassword肯定不应该在模型中,因为它不应该被持久存在。

由于MVC 3的整个不显眼的客户端验证依赖于模型,我不喜欢在我的模型上放置ConfirmPassword属性,我该怎么办?

我应该注入自定义客户端验证函数吗?如果是这样. .如何?

由于MVC 3中不显眼的客户端验证依赖于模型,我不想在我的模特,我该怎么办?

我完全同意你的看法。这就是为什么你应该使用视图模型。然后在你的视图模型上(一个专门为给定视图的需求设计的类),你可以使用[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");
}

看看MVC3应用程序的默认VS2010模板。

它包含一个RegisterModel(一个'ViewModel'),其中包含Password和ConfirmPassword属性。验证设置在ConfirmPassword上。

所以答案是MVC中的模型不必(通常不是)与您的业务模型相同。

最新更新