UserRoles 身份表关系
步骤
编写用于增删用户的 ViewModel
public class UserRoleViewModel
{
public string UserId { get; set; }
public string UserName { get; set; }
public bool IsSelected { get; set; }
}
在 EditRole 页面增加一个导向 EditUsersInRole 的链接
<a class="btn btn-outline-primary" style="width: auto" asp-action="EditUsersInRole" asp-controller="Admin" asp-route-roleid="@Model.Id">从角色中添加或删除用户</a>
跳转到 EditUsersInRole 时,将所有用户的信息传递过来
[HttpGet]
public async Task<IActionResult> EditUsersInRole(string roleId)
{
ViewBag.roleId = roleId;
var role = await _roleManager.FindByIdAsync(roleId);
if (role == null)
{
ViewBag.ErrorMessage = $"角色 ID 为 {roleId} 的角色不存在";
return View("NotFound");
}
var model = new List<UserRoleViewModel>();
foreach (var user in _userManager.Users)
{
var userRoleViewModel = new UserRoleViewModel
{
UserId = user.Id,
UserName = user.UserName,
IsSelected = await _userManager.IsInRoleAsync(user, role.Name)
};
model.Add(userRoleViewModel);
}
return View(model);
}
编写 EditUsersInRole 视图 ```html @model List
@{ ViewBag.Title = “在此角色中添加或删除用户”; var roleId = ViewBag.roleId; }
注:此处推荐使用 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)
5. 编写更新角色用户的 Post 方法
```csharp
[HttpPost]
public async Task<IActionResult> EditUsersInRole(List<UserRoleViewModel> model, string roleId)
{
var role = await _roleManager.FindByIdAsync(roleId);
if (role == null)
{
ViewBag.ErrorMessage = $"角色 ID 为 {roleId} 的角色不存在";
return View("NotFound");
}
for (var i = 0; i < model.Count; i++)
{
var userRoleVM = model[i];
var user = await _userManager.FindByIdAsync(userRoleVM.UserId);
// 判断当前用户是否已属于该角色且被选中
// 不属于的话,要添加进来;没有选中的话要移除出来
var isInRole = await _userManager.IsInRoleAsync(user, role.Name);
IdentityResult result;
// 被选中,但尚不属于该角色
if (userRoleVM.IsSelected && !isInRole)
{
result = await _userManager.AddToRoleAsync(user, role.Name);
}
// 本来属于该角色,但未被选中
else if (!userRoleVM.IsSelected && isInRole)
{
result = await _userManager.RemoveFromRoleAsync(user, role.Name);
}
else continue;
if (result.Succeeded)
{
if (i < model.Count - 1) continue;
return RedirectToAction("EditRole", new { id = roleId });
}
}
return RedirectToAction("EditRole", new { id = roleId });
}