public async Task <IActionResult> Edit(int id, AppUser_Edit userEditVM) { if (id != userEditVM.AppUser.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(userEditVM.AppUser); await _context.SaveChangesAsync(); // handle the change of roles List <AppRole> allRoles = await _context.AppRoles.OrderBy(a => a.RoleName).ToListAsync(); for (int i = 0; i < allRoles.Count; i++) { bool alreadyHasRole = _context.UserRoles .Any(u => u.RoleID == allRoles[i].Id && u.UserID == userEditVM.AppUser.Id); if (userEditVM.HasRole[i] && !alreadyHasRole) // add new role { UserRoles ur = new UserRoles { RoleID = allRoles[i].Id, UserID = userEditVM.AppUser.Id }; await _context.UserRoles.AddAsync(ur); } else if (!userEditVM.HasRole[i] && alreadyHasRole) // remove unchecked role { UserRoles ur = new UserRoles { RoleID = allRoles[i].Id, UserID = userEditVM.AppUser.Id }; _context.UserRoles.Remove(ur); } } await _context.SaveChangesAsync(); TempData["Toast"] = Toasts.Saved; } catch (DbUpdateConcurrencyException) { if (!UserExists(userEditVM.AppUser.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(userEditVM)); }
public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var userEditVM = new AppUser_Edit { AppUser = await _context.AppUsers.Include("Roles.AppRole").FirstOrDefaultAsync(u => u.Id == id), HasRole = new List <bool>() }; if (userEditVM.AppUser == null) { return(NotFound()); } // order roles to match ViewData userEditVM.AppUser.Roles = userEditVM.AppUser.Roles.OrderBy(r => r.AppRole.RoleName).ToList(); var allRoles = _context.AppRoles.AsNoTracking().OrderBy(a => a.RoleName).ToList(); foreach (var role in allRoles) { if (userEditVM.AppUser.Roles.Any(r => r.RoleID == role.Id)) { userEditVM.HasRole.Add(true); } else { userEditVM.HasRole.Add(false); } } ViewDataRoles(); return(View(userEditVM)); }