如何正确实现[确认密码"在ASP.NET MVC 3? [英] How to properly implement "Confirm Password" in ASP.NET MVC 3?

查看:390
本文介绍了如何正确实现[确认密码"在ASP.NET MVC 3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有已经是回答问题大约相同的主题,但因为它是从'09我认为这是过时的。

如何正确实施确认密码中的ASP.NET MVC 3?

我看到网络上有很多选择,他们大多使用 CompareAttribute 在模型中的像这样的

问题是绝对 ConfirmPassword shound't是模型,因为它不应该被保留。

由于从MVC 3全unobstrusive客户端验证依赖模型,我不觉得自己像把一个ConfirmPassword财产上我的模型,我该怎么办?

我应该注入一个自定义的客户端验证功能?如果是这样..如何?


解决方案

  

由于从MVC 3全unobstrusive客户端验证依赖
  模型,我不喜欢把一个ConfirmPassword财产上我
  模型,我该怎么办?


一个完全同意你的看法。这就是为什么你应该使用视图模型。然后在您的视图模型(专为特定视图的要求而设计的一类),你可以使用 [比较] 属性:

 公共类RegisterViewModel
{
    [需要]
    公共字符串用户名{获得;组; }    [需要]
    公共字符串密码{搞定;组; }    [比较(密码的ErrorMessage =确认密码不匹配,再次键入!)
    公共字符串ConfirmPassword {搞定;组; }
}

,然后让你的控制器动作借此视图模型

  [HttpPost]
公众的ActionResult寄存器(RegisterViewModel模型)
{
    如果(!ModelState.IsValid)
    {
        返回查看(模型);
    }    // TODO:视图模型域模型地图和传递到存储库
    //我个人使用和喜欢AutoMapper非常多(HTTP://automapper.$c$cplex.com)    返回RedirectToAction(成功);
}

There's already an answered question about the same subject but as it's from '09 I consider it outdated.

How to properly implement "Confirm Password" in ASP.NET MVC 3?

I'm seeing a lot of options on the Web, most of them using the CompareAttribute in the model like this one

The problem is that definitely ConfirmPassword shound't be in the model as it shouldn't be persisted.

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?

Should I inject a custom client validation function? If so.. How?

解决方案

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?

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:

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");
}

这篇关于如何正确实现[确认密码"在ASP.NET MVC 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆