在MVC中实现[比较(“密码”)]属性 [英] implement [Compare("password")] attribute in MVC

查看:267
本文介绍了在MVC中实现[比较(“密码”)]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用MVC 4中的比较属性来确保用户在注册过程中输入相同的密码两次。我正在使用Code First方法。我的示例模型如下。

I am trying to use the Compare attribute in MVC 4 to ensure user enters the same password twice during registration. I am using Code First approach. My sample model is as follows.

public class Registration
{
    public int RegistrationId { get; set; }
    [Required]
    [StringLength(16, MinimumLength = 6)]
    [Display(Name = "Username")]
    [Remote("CheckUserName", "Home", ErrorMessage="Username is taken.")]
    public string UserName { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Password)]
    public string Password { get; set; }
    [Compare("Password")]
    public string PasswordConfirm { get; set; }
}

唯一的问题是生成的数据库表将包含两个密码字段。有没有一个聪明的方法来避免这个问题?

The only problem with this is that the database table that gets generated would contain two password fields. Is there a smart way to avoid this problem?

推荐答案

假设你使用 entity-framework (你提到的是第一个代码,但没有标记它)您可以使用 [NotMapped] 告诉设计师不要添加列。

Assuming you're using entity-framework (you mentioned code-first but didn't tag it), you can decorate the property with [NotMapped] to tell the designer not to add the column.

但是,这是一个更好的想法,为数据库和视图使用单独的模型,然后映射两个表示或更新。

However, it's a better idea to use separate models for the database and the view, then map the two for presentation or updating.

这篇关于在MVC中实现[比较(“密码”)]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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