1
我想擁有3種不同類型的用戶,但我很困惑如何在EF6中使用MVC5中的新標識進行創建。我應該如何在asp.net MVC5 EF6中使用3種不同的用戶類型進行代碼註冊?
AccountController.cs
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() {
UserName = model.UserName,
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
RegisterViewModel.cs
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { 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")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
// for first name
[Required]
[Display(Name = "First name")]
public string FirstName { get; set; }
//for last name
[Required]
[Display(Name = "Last name")]
public string LastName { get; set; }
//for email
[Required]
[StringLength(60, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
[Display(Name = "Email")]
public string Email { get; set; }
// Return a pre-poulated instance of AppliationUser:
public ApplicationUser GetUser()
{
var user = new ApplicationUser()
{
UserName = this.UserName,
FirstName = this.FirstName,
LastName = this.LastName,
Email = this.Email
};
return user;
}
}
register.cshtml(顯示我只加什麼)
// new properties
<div class="form-group">
@Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
ApplicationUser類
public class ApplicationUser : IdentityUser {
[Required] public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
}
感謝鏈接..但是,這將是巨大的,如果我可以看到一個簡單而明確的解釋例子。謝謝。你有在github上的回購嗎? – Robin