我想将AspNetRoles的角色分配给AspNetUsers中的用户,角色/用户的ID将存储在AspNetUserRoles中。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var currentUser = UserManager.FindByName(user.UserName);
var roleresult = UserManager.AddToRole(currentUser.Id, "//Employee or Admin");
}
我有一个下拉菜单,SuperAdmin将从中选择用户的角色,它可以是Admin或Employee。所以我想获得下拉选择项的值。我怎样才能做到这一点? 感谢。
答案 0 :(得分:1)
如果您希望为可用角色提供一些Select
/下拉列表,并创建具有某个所选角色的用户。您必须为Select
创建RegisterViewModel class property: SelectedRole
/ dropdown元素,并且能够从可用角色列表中选择一个元素。
如何使用您可以找到there的角色填充DropDownList
。
修改了注册视图模型以传输SelectedRole
值:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Role")]
public string SelectedRole { 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; }
}
然后在注册期间,您必须使用viewmodel中的所选角色,并将创建的用户添加到该角色。
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var currentUser = UserManager.FindByName(user.UserName);
var roleresult = UserManager.AddToRole(currentUser.Id, model. SelectedRole);
...
}