public async Task <IActionResult> EditRoles(EditRoles_VM viewmodel) { var user = await _userManager.FindByIdAsync(viewmodel.Id); if (user == null) { return(Redirect("/Error/404")); } foreach (KeyValuePair <string, bool> pair in viewmodel.Roles) { if (pair.Value) { Role role = await _roleManager.FindByNameAsync(pair.Key); if (!await _userManager.IsInRoleAsync(user, role.Name)) { var result = await _userManager.AddToRoleAsync(user, role.Name); if (!result.Succeeded) { return(Redirect("/Error/0")); } } } else { Role role = await _roleManager.FindByNameAsync(pair.Key); if (await _userManager.IsInRoleAsync(user, role.Name)) { var result = await _userManager.RemoveFromRoleAsync(user, role.Name); if (!result.Succeeded) { return(Redirect("/Error/0")); } } } } return(RedirectToAction(nameof(IndexUsers))); }
public async Task <IActionResult> EditRoles(string id) { if (String.IsNullOrEmpty(id)) { return(Redirect("/Error/400")); } User user = await _userManager.FindByIdAsync(id); if (user == null) { return(Redirect("/Error/404")); } EditRoles_VM viewmodel = new EditRoles_VM() { Id = user.Id, Name = user.Name }; foreach (var role in _roleManager.Roles) { viewmodel.Roles.Add(role.Name, await _userManager.IsInRoleAsync(user, role.Name)); } return(View(viewmodel)); }