Diamond Stone
Diamond Stone

Reputation: 115

Add role of a user in asp.net identity?

I want to assign a role from AspNetRoles to a user in AspNetUsers which the Id of both the role/user are to be stored in 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");

        }

I have a dropdown menu from which SuperAdmin will select the Role of the user, it can be Admin or Employee. So I want to get the value of dropdown selected item. How can I do that? Thanks.

Upvotes: 0

Views: 3997

Answers (1)

Andrii Tsok
Andrii Tsok

Reputation: 1446

In case when you want to have some Select/dropdown with available roles and create user with some selected role. You must to create Select/dropdown element for RegisterViewModel class property: SelectedRole with ability to select one element from a list of available roles.

How to populate DropDownList with roles you can find there.

Modified registration viewmodel to transfer SelectedRole value:

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; }
}    

Then during registration you have to use that selected role from your viewmodel and add your created user to that Role.

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);
    ...
}

Upvotes: 1

Related Questions