I want to select role while the user is registered , so How do I combine register with created Roles in Asp.Net mvc5 ?
Loading
I want to select role while the user is registered , so How do I combine register with created Roles in Asp.Net mvc5 ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
malusi ngubanePosted Jul 29, 2015, 5:43 AM
// 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();
}
// Register(RegisterViewModel model,FormCollection form)
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task
{
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);
}
Select User Role: @Html.DropDownList("RoleName", (IEnumerable)ViewBag.Roles, "Select ...")
malusi ngubanePosted Jul 29, 2015, 5:03 AM
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