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

And*_*ena 30 .net asp.net-mvc-3

已经有一个关于同一主题的回答问题,但是从'09我认为它过时了.

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

我在Web上看到很多选项,大多数都使用像这样CompareAttribute的模型

问题是ConfirmPassword在模型中肯定不会因为它不应该被持久化而存在.

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

我应该注入自定义客户端验证功能吗?如果是这样..怎么样?

Dar*_*rov 81

由于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; }
}
Run Code Online (Sandbox Code Playgroud)

然后让您的控制器操作采用此视图模型

[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");
}
Run Code Online (Sandbox Code Playgroud)

  • @jocull,阅读[文档](http://msdn.microsoft.com/en-us/library/system.web.mvc.compareattribute.aspx).汇编:`System.Web.Mvc.dll`.命名空间:`System.Web.Mvc`. (2认同)
  • 在较新的C#中,最好使用[[Compare(nameof(Password),...]),而不是硬编码`Password`属性名。 (2认同)