如何在 ASP.NET MVC 3 中正确实现“确认密码”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6801585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly implement "Confirm Password" in ASP.NET MVC 3?
提问by André Pena
There's already an answered questionabout the same subject but as it's from '09 I consider it outdated.
已经有一个关于同一主题的已回答问题,但由于它是从 09 年开始的,我认为它已经过时了。
How to properly implement "Confirm Password" in ASP.NET MVC 3?
如何在 ASP.NET MVC 3 中正确实现“确认密码”?
I'm seeing a lot of options on the Web, most of them using the CompareAttributein the model like this one
我在网络上看到了很多选项,其中大部分都使用了像这样CompareAttribute的模型
The problem is that definitely ConfirmPasswordshound't be in the model as it shouldn't be persisted.
问题是绝对ConfirmPassword不应该出现在模型中,因为它不应该被持久化。
As the whole unobstrusive client validation from MVC 3 rely on the model and I don't feel like putting a ConfirmPassword property on my model, what should I do?
由于来自 MVC 3 的整个不显眼的客户端验证依赖于模型,我不想在我的模型上放置 ConfirmPassword 属性,我该怎么办?
Should I inject a custom client validation function? If so.. How?
我应该注入自定义客户端验证功能吗?如果是这样..如何?
回答by Darin Dimitrov
As the whole unobstrusive client validation from MVC 3 rely on the model and I don't feel like putting a ConfirmPassword property on my model, what should I do?
由于来自 MVC 3 的整个不显眼的客户端验证依赖于模型,我不想在我的模型上放置 ConfirmPassword 属性,我该怎么办?
A completely agree with you. That's why you should use view models. Then on your view model (a class specifically designed for the requirements of the given view) you could use the [Compare]attribute:
完全同意你的看法。这就是为什么你应该使用视图模型。然后在您的视图模型(专门为给定视图的要求设计的类)上,您可以使用该[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; }
}
and then have your controller action take this view model
然后让您的控制器操作采用此视图模型
[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");
}
回答by Henk Holterman
Take a look at the default VS2010 template for a MVC3 app.
查看 MVC3 应用程序的默认 VS2010 模板。
It contains a RegisterModel(a 'ViewModel') that contains the Password and ConfirmPassword properties. The validation is set on the ConfirmPassword.
它包含一个RegisterModel(一个“ViewModel”),其中包含 Password 和 ConfirmPassword 属性。验证是在 ConfirmPassword 上设置的。
So the answer is that the Models in MVC don't have to be (usually aren't) the same as your business Models.
所以答案是 MVC 中的模型不必(通常不是)与您的业务模型相同。

