有两种型号
用户
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
}
我用来注册用户的和 RegisterUserModel
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; }
}
这是我控制器的方法
[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);
}
我不喜欢设置值
newUser.Type = UserType.User;
newUser.IsActive = true;
手动控制器中的虽然我的用户模型中有这些默认值,但我认为这不是很好的做法,但我不知道如何避免它? / p>
答案 0 :(得分:2)
DefaultValueAttribute
不会按照您的想法执行操作,即实际在属性上设置实际值。如果您希望该属性具有默认值,那么您需要一个自定义的getter和setter:
private UserType? type;
public UserType Type
{
get { return type ?? UserType.User; }
set { type = value; }
}
答案 1 :(得分:1)
在这种情况下,您可以使用属性为User设置值,也可以创建构造函数并在其中设置这些属性。
如果您不想手动设置属性,可以使用AutoMapper(http://automapper.org/)等映射工具为您进行映射。
此致