因需要在用戶列表中點詳情按鈕來到當前頁,所以需要展示分組詳情,並展示當前所屬角色組的用戶
public async Task<ActionResult> Details(string id) { //查找是否存在角色組 var role = await _roleManager.FindByIdAsync(id); //如果角色不存在跳轉回角色列表 if (role == null) { return RedirectToAction(nameof(Index)); } //給視圖模型賦值 var roleUserViewModel = new RoleUserViewModel() { RoleId = role.Id, RoleName = role.Name }; //找出所有用戶 var users = await _userManager.Users.AsNoTracking().ToListAsync(); //循環查找用戶是否存在當前角色組 foreach (var item in users) { if (await _userManager.IsInRoleAsync(item, role.Name)) { roleUserViewModel.Users.Add(item); } } return View(roleUserViewModel); }
詳情展示頁視圖代碼如下
@model Shop.ViewModel.RoleUserViewModel @{ ViewData["Title"] = "Details"; } <h1>Details</h1> <div> <h4>CreateRoleViewModel</h4> <hr /> <dl class="row"> <dt class="col-sm-5"> @Html.DisplayFor(model => model.RoleId) </dt> <dd class="col-sm-2"> @Html.DisplayFor(model => model.RoleName) </dd> </dl> <dl class="row"> @foreach (var item in Model.Users) { <dt>@item.UserName</dt> } </dl> <a asp-action="AddUserToRole" asp-route-id="@Model.RoleId" class="btn btn-success">添加用戶到角色</a> </div> <div> @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) | <a asp-action="Index">Back to List</a> </div>
創建UserRoleViewModel模型類
using System.Collections.Generic; using Microsoft.AspNetCore.Identity; namespace Shop.ViewModel { public class UserRoleViewModel { public UserRoleViewModel() { Users = new List<IdentityUser>(); } public string RoleId { get; set; } public string UserId { get; set; } public List<IdentityUser> Users { get; set; } } }
在role控制器中創建添加用戶到角色組的顯示方法
public async Task<ActionResult> AddUserToRole(string id) { //查找是否存在角色 var role = await _roleManager.FindByIdAsync(id); //如果角色不存在跳回角色列表 if (role == null) { return RedirectToAction(nameof(Index)); } //將查找的角色ID添加到視圖模型 var userRoleViewModel = new UserRoleViewModel() { RoleId = role.Id }; //將所有用戶找出來 var users = await _userManager.Users.AsNoTracking().ToListAsync(); //循環遍歷是否用戶不在當前角色中、 foreach (var item in users) { if (!await _userManager.IsInRoleAsync(item, role.Name)) { userRoleViewModel.Users.Add(item); } } //將視圖模型返回 return View(userRoleViewModel); }
根據選擇添加用戶到角色組
[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> AddUserToRole(UserRoleViewModel input) { //查找當前用戶 var user = await _userManager.FindByIdAsync(input.UserId); //查找當前角色組 var role = await _roleManager.FindByIdAsync(input.RoleId); //角色跟用戶都找到 if (user != null && role != null) { //用戶管理中添加當前用戶到角色組(當前用戶,角色組名稱) var result = await _userManager.AddToRoleAsync(user, role.Name); if (result.Succeeded) { return RedirectToAction(nameof(Index)); } //輸出所有Model級錯誤 foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return View(input); }
頁面顯示,選擇后按添加執行上邊方法寫入數據庫
添加后返回詳情頁,並顯示當前角色組的用戶如圖所示
添加用戶后,再次添加將不再顯示在選擇框內
刪除角色跟添加角色類似,刪除代碼為_userManager.RemoveFromRoleAsync(user,role.Name)