public async Task <ActionResult> UpdateRoles(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Users user = await _unitOfWork.usersRolesRepo.GetAsync((int)id); var roleMap = user.UserRolesMapping; List <CheckBoxRoles> roles = new List <CheckBoxRoles>(); var roleMasters = await _unitOfWork.rolesMappingRepo.GetRoleMastersAsync(); bool IsChecked; foreach (var roleMaster in roleMasters) { CheckBoxRoles cbRoles = new CheckBoxRoles() { ID = roleMaster.ID, Role = roleMaster.RoleName, IsChecked = false }; roles.Add(cbRoles); } RolesUpdateVM model = new RolesUpdateVM() { Id = (int)id, Username = user.Username, MyRoles = RolesToCSV(user), RoleMasters = roles }; TempData["roles"] = roles; return(View(model)); }
public async Task <ActionResult> UpdateRoles([Bind(Include = "Id,Username,MyRoles,RoleMasters")] RolesUpdateVM model) { if (!ModelState.IsValid) { return(View(model)); } if (TempData["roles"] == null) { return(View(model)); } List <CheckBoxRoles> roles = (List <CheckBoxRoles>)TempData["roles"]; Users user = await _unitOfWork.usersRolesRepo.GetAsync(model.Id); var userRoleMaps = user.UserRolesMapping; // Gets the role names to be updated. var rolesAdding = new List <string>(); var rolesRemoving = new List <string>(); foreach (var role in model.RoleMasters) { // assigns the role name to role.Role. role.Role = roles.Where(r => r.ID == role.ID).Select(r => r.Role).FirstOrDefault(); // check if user is in role. UserRolesMapping map = userRoleMaps.Where(r => r.RoleID == role.ID).FirstOrDefault(); if (role.IsChecked && map == null) { map = new UserRolesMapping() { UserID = user.ID, RoleID = role.ID }; _unitOfWork.rolesMappingRepo.Add(map); rolesAdding.Add(role.Role); } else if (!role.IsChecked && map != null) { _unitOfWork.rolesMappingRepo.Remove(map); rolesRemoving.Add(role.Role); } } // Updates user roles in the service's database. if (rolesAdding.Any()) { await _usersRest.AddRolesServiceAsync(user.Username, rolesAdding); } if (rolesRemoving.Any()) { await _usersRest.RemoveRolesServiceAsync(user.Username, rolesRemoving); } await _unitOfWork.SaveAsync(); return(RedirectToAction("Index")); }