UserRoles 身份表关系

image.png

步骤

  1. 编写用于增删用户的 ViewModel

    1. public class UserRoleViewModel
    2. {
    3. public string UserId { get; set; }
    4. public string UserName { get; set; }
    5. public bool IsSelected { get; set; }
    6. }
  2. 在 EditRole 页面增加一个导向 EditUsersInRole 的链接

    1. <a class="btn btn-outline-primary" style="width: auto" asp-action="EditUsersInRole" asp-controller="Admin" asp-route-roleid="@Model.Id">从角色中添加或删除用户</a>
  3. 跳转到 EditUsersInRole 时,将所有用户的信息传递过来

    1. [HttpGet]
    2. public async Task<IActionResult> EditUsersInRole(string roleId)
    3. {
    4. ViewBag.roleId = roleId;
    5. var role = await _roleManager.FindByIdAsync(roleId);
    6. if (role == null)
    7. {
    8. ViewBag.ErrorMessage = $"角色 ID 为 {roleId} 的角色不存在";
    9. return View("NotFound");
    10. }
    11. var model = new List<UserRoleViewModel>();
    12. foreach (var user in _userManager.Users)
    13. {
    14. var userRoleViewModel = new UserRoleViewModel
    15. {
    16. UserId = user.Id,
    17. UserName = user.UserName,
    18. IsSelected = await _userManager.IsInRoleAsync(user, role.Name)
    19. };
    20. model.Add(userRoleViewModel);
    21. }
    22. return View(model);
    23. }
  4. 编写 EditUsersInRole 视图 ```html @model List

@{ ViewBag.Title = “在此角色中添加或删除用户”; var roleId = ViewBag.roleId; }

在此角色中添加或删除用户

@for (var i = 0; i < Model.Count; i++) {
}

  1. 注:此处推荐使用 for 而不是 foreach,直接用 foreach 生成的 checkbox name 有问题。<br />![image.png](https://cdn.nlark.com/yuque/0/2020/png/101969/1585009517576-4373bcdd-1d61-4293-b9b6-77dabf121f87.png#align=left&display=inline&height=349&margin=%5Bobject%20Object%5D&name=image.png&originHeight=349&originWidth=1212&size=71876&status=done&style=none&width=1212)
  2. 5. 编写更新角色用户的 Post 方法
  3. ```csharp
  4. [HttpPost]
  5. public async Task<IActionResult> EditUsersInRole(List<UserRoleViewModel> model, string roleId)
  6. {
  7. var role = await _roleManager.FindByIdAsync(roleId);
  8. if (role == null)
  9. {
  10. ViewBag.ErrorMessage = $"角色 ID 为 {roleId} 的角色不存在";
  11. return View("NotFound");
  12. }
  13. for (var i = 0; i < model.Count; i++)
  14. {
  15. var userRoleVM = model[i];
  16. var user = await _userManager.FindByIdAsync(userRoleVM.UserId);
  17. // 判断当前用户是否已属于该角色且被选中
  18. // 不属于的话,要添加进来;没有选中的话要移除出来
  19. var isInRole = await _userManager.IsInRoleAsync(user, role.Name);
  20. IdentityResult result;
  21. // 被选中,但尚不属于该角色
  22. if (userRoleVM.IsSelected && !isInRole)
  23. {
  24. result = await _userManager.AddToRoleAsync(user, role.Name);
  25. }
  26. // 本来属于该角色,但未被选中
  27. else if (!userRoleVM.IsSelected && isInRole)
  28. {
  29. result = await _userManager.RemoveFromRoleAsync(user, role.Name);
  30. }
  31. else continue;
  32. if (result.Succeeded)
  33. {
  34. if (i < model.Count - 1) continue;
  35. return RedirectToAction("EditRole", new { id = roleId });
  36. }
  37. }
  38. return RedirectToAction("EditRole", new { id = roleId });
  39. }