RolesInUserViewModel:
namespace StudentManagement.ViewModels
{
public class RolesInUserViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public bool IsSelected { get; set; }
}
}
用户角色管理方法:
[HttpGet]
public async Task<IActionResult> ManageUserRoles(string userId)
{
ViewBag.userId = userId;
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"无法找到 Id {userId} 的用户";
return View("NotFound");
}
var model = new List<RolesInUserViewModel>();
foreach (var role in _roleManager.Roles)
{
var rolesInUserViewModel = new RolesInUserViewModel
{
RoleId = role.Id,
RoleName = role.Name,
IsSelected = await _userManager.IsInRoleAsync(user, role.Name)
};
model.Add(rolesInUserViewModel);
}
return View(model);
}
[HttpPost]
public async Task<IActionResult> ManageUserRoles(List<RolesInUserViewModel> model, string userId)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"无法找到 Id {userId} 的用户";
return View("NotFound");
}
var roles = await _userManager.GetRolesAsync(user);
// 移除当前用户中的所有角色信息
var removeRolesResult = await _userManager.RemoveFromRolesAsync(user, roles);
if (!removeRolesResult.Succeeded)
{
ModelState.AddModelError("", "无法删除用户中的现有角色");
return View(model);
}
// 查询出模型列表中选中的 RoleName 添加到用户中
var addRolesResult = await _userManager.AddToRolesAsync(user, model.Where(x => x.IsSelected).Select(y => y.RoleName));
if (!addRolesResult.Succeeded)
{
ModelState.AddModelError("", "无法向用户中添加选定的角色");
return View(model);
}
return RedirectToAction("EditUser", new { Id = userId });
}
用户角色管理视图:
@model List<RolesInUserViewModel>
@{
var userId = ViewBag.userId;
}
<form method="post">
<div class="card">
<div class="card-header">
<h2>管理用户中的角色</h2>
</div>
<div class="card-body">
@for (var i = 0; i < Model.Count; i++)
{
<div class="form-check m-1">
<input type="hidden" asp-for="@Model[i].RoleId" />
<input type="hidden" asp-for="@Model[i].RoleName" />
<input asp-for="@Model[i].IsSelected" class="form-check-input" />
<label class="form-check-label" asp-for="@Model[i].IsSelected">
@Model[i].RoleName
</label>
</div>
}
<div asp-validation-summary="All" class="text-danger"></div>
</div>
<div class="card-footer">
<input type="submit" value="更新" class="btn btn-primary" style="width: auto" />
<a class="btn btn-primary" style="width: auto" asp-action="EditUser" asp-route-id="@userId">取消</a>
</div>
</div>
</form>
效果: