我正在尝试使用MVC 4中的Compare
属性来确保用户在注册期间两次输入相同的密码。我正在使用Code First方法。我的样本模型如下。
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; }
}
唯一的问题是生成的数据库表将包含两个密码字段。有没有一种聪明的方法来避免这个问题?
答案 0 :(得分:3)
假设您正在使用entity-framework(您提到代码优先但未对其进行标记),您可以使用[NotMapped]
修饰该属性,以告知设计人员不要添加该列。
然而,对于数据库和视图使用单独的模型是一个更好的想法,然后将两者映射以进行演示或更新。
答案 1 :(得分:3)
正确的方法是使用View Models而不是将您的实体对象用作View Models。您永远不应该将实体模型绑定到View。只是说...
public class RegistrationViewModel
{
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; }
}
public class Registration
{
public int RegistrationId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}