public async Task <IActionResult> EditUser(string id) { var user = await this.CompanyWorkData.Users.GetById(id); if (user == null) { this.logger.LogError(2, $"User with Id {id} not found."); return(NotFound($"User with Id {id} not found.")); } return(View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper))); }
public async Task <IActionResult> EditUser(EditUserViewModel model) { var user = await this.userManager.FindByIdAsync(model.Id); if (user == null) { this.logger.LogError(2, $"User with Id {model.Id} not found."); return(NotFound($"User with Id {model.Id} not found.")); } if (!ModelState.IsValid) { return(View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper))); } if (!(await this.userManager.IsInRoleAsync(user, model.ApplicationRoleName))) { var newRole = await this.roleManager.FindByNameAsync(model.ApplicationRoleName); if (newRole == null) { ModelState.AddModelError( string.Empty, $"Application role {model.ApplicationRoleName} not found."); ModelState.Values.ToList() .ForEach(m => m.Errors.ToList() .ForEach(e => this.logger.LogError(2, e.ErrorMessage))); return(View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper))); } var oldRoles = await this.userManager.GetRolesAsync(user); await this.userManager.RemoveFromRolesAsync(user, oldRoles); await this.userManager.AddToRoleAsync(user, newRole.Name); } user.UpdatePhone(model.PhoneNumber); var result = await this.userManager.UpdateAsync(user); if (!result.Succeeded) { this.AddErrors(result); return(View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper))); } this.logger.LogInformation(3, string.Format("Admin edited User with Id {0}.", user.Id)); return(RedirectToAction(nameof(ShowAllUsers))); }