public ActionResult ModifyGivenRole(string userId) { if (userId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ApplicationDbContext db = new ApplicationDbContext(); UserManager <ApplicationUser> UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db)); RoleManager <IdentityRole> RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(db)); ApplicationUser user = UserManager.FindById(userId); var rolesForUser = UserManager.FindById(userId).Roles; var users = from u in context.Users where u.Id == userId select new { UserId = u.Id, Name = u.UserName, Email = u.Email }; foreach (var item in rolesForUser) { IdentityRole role = RoleManager.FindById(item.RoleId); currentrole = role.Name; } UserAndRolesModel urm = new UserAndRolesModel(); urm.Username = user.UserName; urm.Role = currentrole; List <SelectListItem> list = context.Roles.Where(r => r.Name == "Admin" || r.Name == "User").OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); ViewBag.ddl = new SelectList(list, "Value", "Text", currentrole); return(PartialView("ModifyGivenRole", urm)); }
public ActionResult ModifyGivenRole(UserAndRolesModel um, string ddl) { ApplicationDbContext db = new ApplicationDbContext(); UserManager <ApplicationUser> UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db)); RoleManager <IdentityRole> RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(db)); var rolesForUser = UserManager.FindById(um.UserId).Roles; ApplicationUser user = UserManager.FindById(um.UserId); foreach (var item in rolesForUser) { IdentityRole role = RoleManager.FindById(item.RoleId); currentrole = role.Name; } if (ModelState.IsValid) { UserManager.RemoveFromRole(user.Id, currentrole); UserManager.AddToRole(user.Id, ddl); return(RedirectToAction("Index")); } else { return(PartialView(um)); } }