1

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?

2 Answers 2

4

Assuming you're using (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.

Sign up to request clarification or add additional context in comments.

Comments

4

The proper approach would be to use View Models instead of using your entity objects as View Models. You should never bind an entity model to a View. Just saying...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.