Home > Net >  User Registration with roles
User Registration with roles

Time:12-13

I have searched over stackoverflow but can't find the exact answer of my question.

I have a signup page where I have to register user with a role that I have already entered in AspNetRoles. I don't understand what the problem whenever I run a code, it gives error System.InvalidOperationException: Role xx does not exist. AccountViewModel

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    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")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public string Name { get; set; }
}

AccountController

    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        //ViewBag.Name = new SelectList(_context.Roles.ToList(), "Name", "Name");
        ViewBag.Name = _context.Roles.Select(b => new SelectListItem { Value = b.Name, Text = b.Name });
        return View();
    }

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var UserPassword = model.Password;
            
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                Session.Add("UserName", user.Email);
                int role = 10;
                
                //Assign Role to user Here. Error is Here 
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                //Ends Here

                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                return RedirectToAction("Index", "Home", new { user.Email, user.PasswordHash });
            }
            AddErrors(result);
        }

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

Register.cshtml

@model ASPNetIdentity.Models.RegisterViewModel

    <!--Select the Role Type for the User.-->
    <div >
        @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
        <div >
            @Html.DropDownListFor(m => m.Name, ViewBag.Name as SelectList, "--Select Role--", new { @class = "form-control" })
        </div>
    </div>
            <!--Ends Here-->                
           

But the error page:enter image description here

Need help Regards

CodePudding user response:

I don't know the content of AddToRoleSync method but in my opinion, You should get the role id from Model.Name property and after that you should add role by id value.

Or you can create select list by id as Value and Name as text.

And in my opinion you should add required validation to your selectlist to assign a role by force.

I hope that this comment will be useful to you

CodePudding user response:

You are passing the wrong parameters, if you read the docs, here it says to pass TUser https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.addtoroleasync?view=aspnetcore-6.0

Parameters

user TUser The user to add to the named role.

role String The name of the role to add the user to. correct usage is:

var userResult = await this.UserManager.AddToRoleAsync(user, model.Name);
  • Related