Example #1
0
        public async Task <IActionResult> UpdateRole(string id)
        {
            var role = await _roleManager.FindByIdAsync(id);

            var users   = _userManager.Users;
            var usersVM = new List <AdminUserRoleVM>();

            foreach (var user in users)
            {
                usersVM.Add(new AdminUserRoleVM()
                {
                    RoleId    = role.Id,
                    RoleName  = role.Name,
                    UserId    = user.Id,
                    UserName  = user.UserName,
                    IsChecked = await _userManager.IsInRoleAsync(user, role.Name)
                });
            }

            var model = new AdminUpdateRoleVM()
            {
                Id               = role.Id,
                Name             = role.Name,
                ApplicationUsers = usersVM
            };

            ViewBag.Title = "Update role";

            return(View(model));
        }
Example #2
0
        public async Task <IActionResult> UpdateRole(AdminUpdateRoleVM model)
        {
            if (ModelState.IsValid)
            {
                var role = await _roleManager.FindByIdAsync(model.Id);

                if (role == null)
                {
                    TempData["RoleNotFound"] = $"There is no role with Id {role.Id}";

                    return(RedirectToAction("RolesOverview"));
                }

                role.Name = model.Name;

                foreach (var user in model.ApplicationUsers)
                {
                    var u = await _userManager.FindByIdAsync(user.UserId);

                    if (user.IsChecked)
                    {
                        await _userManager.AddToRoleAsync(u, role.Name);
                    }
                    else
                    {
                        await _userManager.RemoveFromRoleAsync(u, role.Name);
                    }
                }

                var result = await _roleManager.UpdateAsync(role);

                if (result.Succeeded)
                {
                    TempData["RoleUpdated"] = $"Role {role.Name} has been updated.";

                    return(RedirectToAction("RolesOverview"));
                }

                TempData["RoleNotUpdated"] = $"Role {role.Name} could not be updated.";

                return(RedirectToAction("RolesOverview"));
            }

            ViewBag.Title = "Update role";

            return(View(model));
        }