分配用户给角色,跟分配角色给用户操作是基本一致的。
打开模块维护,展开SysRole模块添加一个操作码,并赋予权限
设置好之后将权限授权给管理员,在SysRole的index添加操作码与js事件
@Html.ToolButton("btnAllot", "icon-share", "分配用户", perm, "Allot", true)
$("#btnAllot").click(function () { var row = $('#List').datagrid('getSelected'); if (row != null) { $("#modalwindow").html("<iframe width='100%' height='100%' scrolling='no' frameborder='0' src='/SysRole/GetUserByRole?roleId=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>"); $("#modalwindow").window({ title: '分配用户', 720, height: 400, iconCls: 'icon-edit' }).window('open'); } else { $.messageBox5s('提示', '请选择一个需要分配用户的角色'); } });
由于和26讲基本一致,只是User改成Role,Role改成User
在SysRoleController添加以下3个方法
#region 设置角色用户 [SupportFilter(ActionName = "Allot")] public ActionResult GetUserByRole(string roleId) { ViewBag.RoleId = roleId; ViewBag.Perm = GetPermission(); return View(); } [SupportFilter(ActionName="Allot")] public JsonResult GetUserListByRole(GridPager pager,string roleId) { if (string.IsNullOrWhiteSpace(roleId)) return Json(0); var userList = m_BLL.GetUserByRoleId(ref pager, roleId); var jsonData = new { total = pager.totalRows, rows = ( from r in userList select new SysUserModel() { Id = r.Id, UserName = r.UserName, TrueName = r.TrueName, Flag = r.flag == "0" ? "0" : "1", } ).ToArray() }; return Json(jsonData); } #endregion [SupportFilter(ActionName = "Save")] public JsonResult UpdateUserRoleByRoleId(string roleId,string userIds) { string[] arr = userIds.Split(','); if (m_BLL.UpdateSysRoleSysUser(roleId,arr)) { LogHandler.WriteServiceLog(GetUserId(), "Ids:" + arr, "成功", "分配用户", "角色设置"); return Json(JsonHandler.CreateMessage(1, Suggestion.SetSucceed), JsonRequestBehavior.AllowGet); } else { string ErrorCol = errors.Error; LogHandler.WriteServiceLog(GetUserId(), "Ids:" + arr, "失败", "分配用户", "角色设置"); return Json(JsonHandler.CreateMessage(0, Suggestion.SetFail), JsonRequestBehavior.AllowGet); } }
GetUserByRole为弹出视图
GetUserListByRole为根据选择的用户获取角色并让已经分配的角色呈现选择状态 (存储过程实现)
Create proc [dbo].[P_Sys_GetUserByRoleId] @RoleId varchar(50) as begin --读取角色所包含的用户 select a.*,ISNULL(b.SysUserId,0) as flag from SysUser a left join SysRoleSysUser b on a.Id=b.SysUserId and b.SysRoleId=@RoleId order by b.SysRoleId desc end
UpdateUserRoleByRoleId更新选择的后的情况(存储过程实现)
Create PROCEDURE [dbo].[P_Sys_UpdateSysRoleSysUser] @roleId varchar(50),@userId varchar(50) AS --更新角色用户中间关系表 BEGIN insert into SysRoleSysUser(SysRoleId,SysUserId) values(@roleId,@userId) END
添加BLL方法
/// <summary> /// 获取角色对应的所有用户 /// </summary> /// <param name="roleId">角色id</param> /// <returns></returns> public string GetRefSysUser(string roleId) { string UserName = ""; var userList = m_Rep.GetRefSysUser(db, roleId); if (userList != null) { foreach (var user in userList) { UserName += "[" + user.UserName + "] "; } } return UserName; } public IQueryable<P_Sys_GetUserByRoleId_Result> GetUserByRoleId(ref GridPager pager, string roleId) { IQueryable<P_Sys_GetUserByRoleId_Result> queryData = m_Rep.GetUserByRoleId(db, roleId); pager.totalRows = queryData.Count(); queryData = m_Rep.GetUserByRoleId(db, roleId); return queryData.Skip((pager.page - 1) * pager.rows).Take(pager.rows); } public bool UpdateSysRoleSysUser(string roleId, string[] userIds) { try { m_Rep.UpdateSysRoleSysUser(roleId, userIds); return true; } catch (Exception ex) { ExceptionHander.WriteException(ex); return false; } }
添加DAL方法
public IQueryable<SysUser> GetRefSysUser(DBContainer db, string id) { if (!string.IsNullOrEmpty(id)) { return from m in db.SysRole from f in m.SysUser where m.Id == id select f; } return null; } public IQueryable<P_Sys_GetUserByRoleId_Result> GetUserByRoleId(DBContainer db, string roleId) { return db.P_Sys_GetUserByRoleId(roleId).AsQueryable(); } public void UpdateSysRoleSysUser(string roleId,string[] userIds) { using(DBContainer db = new DBContainer()) { db.P_Sys_DeleteSysRoleSysUserByRoleId(roleId); foreach (string userid in userIds) { if (!string.IsNullOrWhiteSpace(userid)) { db.P_Sys_UpdateSysRoleSysUser(roleId, userid); } } db.SaveChanges(); } }
新角色用户中间关系表,前删除关联
Create PROCEDURE [dbo].[P_Sys_DeleteSysRoleSysUserByRoleId] @roleId varchar(50) AS --更新角色用户中间关系表,前删除关联 BEGIN delete SysRoleSysUser where SysRoleId=@roleId END
自行添加BLL和DAL的接口方法
添加GetUserByRole.cshtml视图
@using App.Admin; @using App.Common; @using App.Models.Sys; @{ ViewBag.Title = "设置角色包含的用户"; Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml"; List<permModel> perm = (List<permModel>)ViewBag.Perm; if (perm == null) { perm = new List<permModel>(); } } <div class="mvctool bgb"> @Html.ToolButton("btnSave", "icon-save", "保存", perm, "Create", true) </div> <div class="pd3"> <table id="RoleList"></table> </div> @*Jqgrid*@ <script type="text/javascript"> $(function () { $('#RoleList').datagrid({ url: '/SysRole/GetUserListByRole?roleId=@(ViewBag.RoleId)', SetGridWidthSub(6), methord: 'post', height: SetGridHeightSub(41), fitColumns: true, sortName: 'Id', sortOrder: 'desc', idField: 'Id', pageSize: 12, pageList: [12, 20, 30, 40, 50], pagination: true, striped: true, //奇偶行是否区分 singleSelect: true,//单选模式 columns: [[ { field: 'Id', title: 'ID', 80, hidden: true }, { field: 'UserName', title: '用户名', 120 }, { field: 'TrueName', title: '姓名', 80 }, { field: 'Flag', title: '是否分配', 80, editor: { type: 'checkbox', options: { on: '1', off: '0' } } } ]], onLoadSuccess: function () { var rows = $("#RoleList").datagrid("getRows"); for (var i = 0; i < rows.length; i++) { //获取每一行的数据 $('#RoleList').datagrid('beginEdit', i); } } }); }); </script> @*operation*@ <script type="text/javascript"> $(function () { $("#btnSave").click(function () { var rows = $("#RoleList").datagrid("getRows"); //这段代码是获取当前页的所有行。 var data = new Array(); for (var i = 0; i < rows.length; i++) { var setFlag = $("td[field='Flag'] input").eq(i).prop("checked"); if (setFlag)//判断是否有作修改 { data.push(rows[i].Id); } } var userIds = data.join(); //提交数据库 $.post("/SysRole/UpdateUserRoleByRoleId", { roleId: '@(ViewBag.RoleId)', userIds: userIds }, function (data) { if (data.type == 1) { window.parent.frameReturnByMes(data.message); window.parent.frameReturnByReload(true); window.parent.frameReturnByClose() } else { window.parent.frameReturnByMes(data.message); } }, "json"); }); }); </script>
理论上效果都会出来。