public async Task <ActionResult> EditUser(string id) { var user = GetUserOrThrow(id); var roles = await _userManager.GetRolesAsync(id); var model = new EditModel { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, MobilePhone = user.MobilePhone, Email = user.Email, IsAdministrator = roles.Contains(Role.Administrator), IsAccountant = roles.Contains(Role.Accountant) }; return(View(nameof(EditUser), model)); }
public async Task <ActionResult> EditUser(string id, EditModel model) { if (ModelState.IsValid) { var user = GetUserOrThrow(id); var roles = await _userManager.GetRolesAsync(user.Id); user.FirstName = model.FirstName; user.LastName = model.LastName; user.MobilePhone = model.MobilePhone; user.UserName = model.Email; user.Email = model.Email; var results = new List <IdentityResult> { await _userManager.UpdateAsync(user) }; if (model.IsAdministrator) { if (!roles.Contains(Role.Administrator)) { results.Add(await _userManager.AddToRoleAsync(user.Id, Role.Administrator)); } } else { if (roles.Contains(Role.Administrator)) { results.Add(await _userManager.RemoveFromRoleAsync(user.Id, Role.Administrator)); } } if (model.IsAccountant) { if (!roles.Contains(Role.Accountant)) { results.Add(await _userManager.AddToRoleAsync(user.Id, Role.Accountant)); } } else { if (roles.Contains(Role.Accountant)) { results.Add(await _userManager.RemoveFromRoleAsync(user.Id, Role.Accountant)); } } if (!string.IsNullOrEmpty(model.Password)) { results.AddRange(new[] { await _userManager.RemovePasswordAsync(user.Id), await _userManager.AddPasswordAsync(user.Id, model.Password) }); } if (results.All(x => x.Succeeded)) { return(this.RedirectToAction(x => x.ListUsers())); } foreach (var error in results.SelectMany(x => x.Errors)) { ModelState.AddModelError(string.Empty, error); } } return(View(nameof(EditUser), model)); }