Search code examples
c#asp.net-mvcvisual-studio-2015asp.net-coreasp.net-identity-2

Adding a dropdown of Roles in the built-in Register.cshtml view and retrieving its selected value in the Reginster action method


I've an ASP.NET Core app with Individual User Accounts authentication. The app by default creates AccountController, RegisterViewModel, Register.cshtml etc as shown below. I've added two properties for a Role dropdown in the RegisterViewModel and I'm displaying that dropdown in the Register.cshtml view so an admin can select a role for a newly created user.

Question: In the following Post method for Register, how do I retrieve the role admin selected from the Register.cshtml view? In other words, in this Post action method how do I use that selected role so I can add the newly created user to that role?

RegisterViewModel:

public class RegisterViewModel
{
        [Required]
        [Display(Name = "Login")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} 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; }

        [Display(Name = "Select Role")]
        public ApplicationRole SelectedRole { get; set; }
        public IEnumerable<SelectListItem> Roles { get; set; }
}

AccountController Action Method:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, StateID=model.StateID, Region=model.Region };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation(3, "User created a new account with password.");
                    return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

Solution

  • to your view model add a selected parameter

    [Display(Name = "Selected Role")]
        public int SelectedRole{ get; set; }
    

    then on your view setup the drop down like this

    @Html.DropDownListFor(x => x.SelectedRole, model.Roles)
    

    this will tie the result of the drop down to your model. then on your controller model.SelectedRole should have your selected id