您需要在RegisterModel
下面添加这些属性:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
//Put annotatons as needed
public string FirstName {get;set;}
public string LastName {get;set;}
}
在此之后,您需要使用Register
in 方法将这些详细信息放入数据库中AccountController
。这可以通过UserId
从数据库中获取Membership
并将额外的详细信息放在与此完全不同的表中来管理。该UserId
表可以如下所示:
public class ExtendedUser
{
[Key]
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
因此Register
,您的方法已[HttpPost]
对以下内容进行了注释,以将数据存储在上表中。
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
//Get UserId for registered user
var UserId = (Guid)Membership.GetUser(model.UserName).ProviderUserKey;
ExtendedUser extrainfo = new ExtendedUser();
extrainfo.UserId = UserId;
extrainfo.FirstName= model.FirstName;
extrainfo.LastName= model.LastName;
//Add this info to database
db.ExtendedUsers.Add(extrainfo);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
当然,您需要将这个新表添加到从类继承的DbContext
类中,如下所示:
public class YourContext: DbContext
{
public DbSet<ExtendedUser> ExtendedUsers{ get; set; }
}
嘘……你就完了。
编辑 :
微软在How to: Implement a Custom Membership User中以不同的方式做到了这一点,但他们在那里遗漏了一些东西。但是你可以看看它。