There are two models
User
public class User
{
private const int NameLength = 200;
private const int EmailLength = 100;
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(NameLength)]
public string Name { get; set; }
[Required]
[EmailAddress]
[StringLength(EmailLength)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(200)]
public string Password { get; set; }
public string PasswordSalt { get; set; }
[Required]
[DefaultValue(UserType.User)]
public UserType Type { get; set; }
[DefaultValue(true)]
public bool IsActive { get; set; }
public virtual List<Task> Tasks { get; set; }
public User()
{
Tasks = new List<Task>();
}
}
[Flags]
public enum UserType
{
Admin = 0,
User = 1
}
and RegisterUserModel which I use to register user
public class RegisterUserModel
{
private const int NameLength = 200;
private const int EmailLength = 100;
private const int PasswordMinLength = 5;
private const int PasswordMaxLength = 20;
[Key]
public int Id { get; set; }
[Required]
[StringLength(NameLength)]
public string Name { get; set; }
[Required]
[EmailAddress]
[StringLength(EmailLength)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(PasswordMaxLength, MinimumLength = PasswordMinLength)]
public string Password { get; set; }
}
and this is method from my controller
[HttpPost]
[AjaxAction]
public ActionResult Registration(RegisterUserModel registerUser)
{
if (ModelState.IsValid)
{
if (!IsUserExist(registerUser.Email))
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(registerUser.Password);
var newUser = db.Users.Create();
newUser.Name = registerUser.Name;
newUser.Email = registerUser.Email;
newUser.Type = UserType.User;
newUser.IsActive = true;
newUser.Password = encrpPass;
newUser.PasswordSalt = crypto.Salt;
db.Users.Add(newUser);
db.SaveChanges();
FormsAuthentication.SetAuthCookie(newUser.Email, false);
return Json(new {status = "OK", message = "Success"}, JsonRequestBehavior.AllowGet);
}
return Json(new { status = "ERROR", message = "User already exists" }, JsonRequestBehavior.AllowGet);
}
return Json(new { status = "ERROR", message = "Data is incorrect" }, JsonRequestBehavior.AllowGet);
}
And I don't like I need to set values
newUser.Type = UserType.User;
newUser.IsActive = true;
in controller manually although I have these default values in my User model, I think it's not very good practice, but I don't know how to avoid it?