Skip to content

Combining Register and Roles

Bandisiwe Spiva

Asked Jul 29, 2015, 12:36 AM EDT2 answers
Share
LinkedInX

 I want to select role while the user is registered , so How do I  combine register with created Roles in Asp.Net mvc5 ?

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • +1

    You will have to Add some code in the //Account Controller /Register method

    and then Add a dropdown list that containing the list of particular roles that you have created in the register View
     

    +1
  • 0

    // GET: /Account/Register
            [AllowAnonymous]
            public ActionResult Register()
            {
              
                ApplicationDbContext context = new ApplicationDbContext();
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;
                return View();
            }

            //
            // POST: /Account/Register
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task Register(RegisterViewModel model,FormCollection form)
            {
                string roleName = form["RoleName"].ToString();
                var account = new AccountController();
              
                if (ModelState.IsValid)
                {
                  
                    var user = new ApplicationUser()
                    {
                        UserName = model.UserName,
                        Email=model.Email,
                        FullName=model.FullName,
                        PhoneNumber=model.PhoneNumber,
                      

                    };
                   
                    //ApplicationDbContext context = new ApplicationDbContext();
                    //UserManager.AddToRole(model.Id, roleName);
                   
                    //ApplicationDbContext context = new ApplicationDbContext();

                  
                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        account.UserManager.AddToRole(user.Id, roleName);
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }

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

     
     
    // View  
     

    Select User Role: @Html.DropDownList("RoleName", (IEnumerable)ViewBag.Roles, "Select ...")

     
    0