索引
【無私分享:從入門到精通ASP.NET MVC】從0開始,一起搭框架、做項目 目錄索引
簡述
今天我們來做角色的管理 和 角色權限分配
項目准備
我們用的工具是:VS 2013 + SqlServer 2012 + IIS7.5
希望大家對ASP.NET MVC有一個初步的理解,理論性的東西我們不做過多解釋,有些地方不理解也沒關系,會用就行了,用的多了,用的久了,自然就理解了。
項目開始
一、新建角色控制器 RoleController 同樣繼承 BaseController
首先,我們來聲明一下需要的接口(注意 xml配置注入 前面文章有詳細步驟 這里不解釋了)
1、然后我們來修改一下視圖Index ,添加權限控制
1 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "View")] 2 public ActionResult Index() 3 { 4 5 return View(); 6 7 }
2、我們來處理一下查詢參數 角色我們是分系統的,所以前台會有一個系統的選擇,還有關鍵字查詢(這個我們通過BaseController 來傳遞,我們這里只是定義一個參數傳給視圖,讓搜索過的關鍵字在文本框中顯示)
先給大家看一下前台的頁面效果
1 /// <summary> 2 /// 加載主頁 3 /// </summary> 4 /// <returns></returns> 5 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "View")] 6 public ActionResult Index() 7 { 8 try 9 { 10 #region 處理查詢參數 11 12 //系統ID 13 string System = Request.QueryString["System"]; 14 ViewData["System"] = System; 15 16 //搜索的關鍵字(用於輸出給前台的Input顯示) 17 ViewBag.Search = base.keywords; 18 #endregion 19 20 //輸出用戶所擁有的系統列表到視圖頁 21 ViewData["Systemlist"] = this.SystemManage.LoadSystemInfo(CurrentUser.System_Id); 22 23 //輸出分頁查詢列表 24 return View(BindList(System)); 25 } 26 catch (Exception e) 27 { 28 WriteLog(Common.Enums.enumOperator.Select, "加載角色列表:", e); 29 throw e.InnerException; 30 } 31 }
3、我們待會做視圖頁的時候在處理 ViewData["System"]、ViewData["Systemlist"]和ViewBag.Search
我們先來處理一下 輸出列表 BindList(System) ,新建一個私有方法 private Common.PageInfo BindList(string system) 輸出結果為 Common.PageInfo
1 /// <summary> 2 /// 分頁查詢角色列表 3 /// </summary> 4 private Common.PageInfo BindList(string system) 5 { 6 7 }
4、首先預加載一下基礎數據
1 //基礎數據 2 var query = this.RoleManage.LoadAll(null);
5、傳遞的系統ID(正常來說 如果傳入系統ID 那么就查詢系統下的角色,如果沒有傳遞就查詢全部系統角色,但是我們這個是分系統控制的,所以,當沒有系統ID傳入的時候,我們查詢用戶可操作的系統的角色)
1 //系統 2 if(!string.IsNullOrEmpty(system)) 3 { 4 int SuperAdminId = Common.Enums.ClsDic.DicRole["超級管理員"]; 5 query = query.Where(p => p.FK_BELONGSYSTEM == system || p.ISCUSTOM == true); 6 } 7 else 8 { 9 query = query.Where(p => this.CurrentUser.System_Id.Any(e => e == p.FK_BELONGSYSTEM)); 10 }
6、關鍵字的查詢(這個keywords是通過BaseController傳遞的)
1 //查詢關鍵字 2 if (!string.IsNullOrEmpty(keywords)) 3 { 4 query = query.Where(p => p.ROLENAME.Contains(keywords)); 5 }
7、排序 分頁
1 //排序 2 query = query.OrderByDescending(p => p.CREATEDATE); 3 //分頁 4 var result = this.RoleManage.Query(query, page, pagesize);
8、要展示的視圖內容
1 var list = result.List.Select(p => new 2 { 3 //以下是視圖需要展示的內容,加動態可循環 4 p.CREATEDATE, 5 p.ROLENAME, 6 p.ROLEDESC, 7 USERNAME = p.CREATEPERID, 8 p.ID, 9 SYSNAME = SystemManage.Get(m=>m.ID==p.FK_BELONGSYSTEM).NAME, 10 ISCUSTOMSTATUS = p.ISCUSTOM ? "<i class=\"fa fa-circle text-navy\"></i>" : "<i class=\"fa fa-circle text-danger\"></i>" 11 }).ToList();
9、返回分頁內容列表
1 return new Common.PageInfo(result.Index, result.PageSize, result.Count, Common.JsonConverter.JsonClass(list));
10、完整的方法

1 /// <summary> 2 /// 分頁查詢角色列表 3 /// </summary> 4 private Common.PageInfo BindList(string system) 5 { 6 //基礎數據 7 var query = this.RoleManage.LoadAll(null); 8 //系統 9 if(!string.IsNullOrEmpty(system)) 10 { 11 int SuperAdminId = Common.Enums.ClsDic.DicRole["超級管理員"]; 12 query = query.Where(p => p.FK_BELONGSYSTEM == system || p.ISCUSTOM == true); 13 } 14 else 15 { 16 query = query.Where(p => this.CurrentUser.System_Id.Any(e => e == p.FK_BELONGSYSTEM)); 17 } 18 //查詢關鍵字 19 if (!string.IsNullOrEmpty(keywords)) 20 { 21 query = query.Where(p => p.ROLENAME.Contains(keywords)); 22 } 23 //排序 24 query = query.OrderByDescending(p => p.CREATEDATE); 25 //分頁 26 var result = this.RoleManage.Query(query, page, pagesize); 27 28 var list = result.List.Select(p => new 29 { 30 //以下是視圖需要展示的內容,加動態可循環 31 p.CREATEDATE, 32 p.ROLENAME, 33 p.ROLEDESC, 34 USERNAME = p.CREATEPERID, 35 p.ID, 36 SYSNAME = SystemManage.Get(m=>m.ID==p.FK_BELONGSYSTEM).NAME, 37 ISCUSTOMSTATUS = p.ISCUSTOM ? "<i class=\"fa fa-circle text-navy\"></i>" : "<i class=\"fa fa-circle text-danger\"></i>" 38 }).ToList(); 39 40 return new Common.PageInfo(result.Index, result.PageSize, result.Count, Common.JsonConverter.JsonClass(list)); 41 }
11、我們進入視圖頁
首先接收一下 分頁列表內容
1 @{ 2 Layout = "~/Views/Shared/_Layout.cshtml"; 3 } 4 @model Common.PageInfo
12、標題和權限標簽
1 <div class="ibox-title"> 2 <h5>角色管理</h5> 3 <div class="ibox-tools"> 4 <a class="btn btn-primary btn-xs p210" id="insert" action="add"><i class="fa fa-plus-circle fa-fw"></i> 創建新角色</a> 5 <a class="btn btn-warning btn-xs p210" id="modify" action="edit"><i class="fa fa-pencil fa-fw"></i> 編輯</a> 6 <a class="btn btn-danger btn-xs p210" id="delete" action="remove"><i class="fa fa-trash-o fa-fw"></i> 刪除</a> 7 <a class="btn btn-info btn-xs p210" id="permission" action="allocation"><i class="fa fa-sheqel fa-fw"></i> 分配權限</a> 8 <a class="reload-link" style="color: #c4c4c4" href="javascript:dig.reload()" data-toggle="tooltip" data-placement="left" title="刷新"> 9 <i class="fa fa-repeat fa-lg"></i> 10 </a> 11 </div> 12 </div>
13、然后我們創建個查詢表單,當用戶切換系統或輸入關鍵字查詢的時候,重新獲取數據
14、輸出角色列表(這里做了個判斷,因為超級管理員是我們內置角色,我們不允許用戶修改)
15、分頁
16、添加修改刪除等 Js方法

1 @section scripts{ 2 <script type="text/javascript"> 3 $(function () { 4 //添加新角色 5 $("#insert").click(function () { 6 dig.addPage("添加新角色", "/Sys/role/detail?systemId=" + $("#System").val(), 600, 450, function () { 7 if (this.returnValue == 'yes') { 8 location.reload(); 9 } 10 }); 11 }); 12 //列表選擇修改 13 $('#modify').click(function () { 14 var vals = ''; 15 var num = 0; 16 $('input[name="checkbox_name"]:checked').each(function () { 17 vals = $(this).val(); 18 num++; 19 }); 20 if (!vals) { 21 dig.error("對不起,請選中您要操作的記錄!"); 22 return; 23 } 24 if (num > 1) { 25 dig.error("對不起,每次只能修改一條記錄!"); 26 return; 27 } 28 dig.addPage("編輯角色", "/Sys/role/detail/" + vals, 600, 450, function () { 29 if (this.returnValue == 'yes') { 30 location.reload(); 31 } 32 }); 33 }); 34 //分配權限 35 $('#permission').click(function () { 36 var vals = ''; 37 var num = 0; 38 $('input[name="checkbox_name"]:checked').each(function () { 39 vals = $(this).val(); 40 num++; 41 }); 42 if (!vals) { 43 dig.error("對不起,請選中您要操作的記錄!"); 44 return; 45 } 46 if (num > 1) { 47 dig.error("對不起,每次只能給一個角色分配權限!"); 48 return; 49 } 50 dig.addPage('分配權限', '/Sys/Permission/PerAllocation/?id=' + vals + '&tp=role', 1000, 500, function () { 51 if (this.returnValue == 'yes') { 52 location.reload(); 53 } 54 }); 55 }); 56 }); 57 //跳轉修改 58 function EditRole(n) { 59 dig.addPage("編輯角色", "/Sys/role/detail/" + n, 600, 450, function () { 60 if (this.returnValue == 'yes') { 61 location.reload(); 62 } 63 }); 64 } 65 </script> 66 }
二、添加模塊和權限
1、這樣我們的角色管理首頁列表就完成了,我們前面已經做完了模塊管理和權限管理,我們來添加一下模塊
模塊管理 → 添加新模塊(選擇上級模塊 系統管理)或直接點擊 系統管理的 [添加子模塊] ,注意模塊別名
2、添加完模塊后,我們刷新頁面發現沒有展示出來,那是因為還沒有權限,我們來添加一下權限
選擇左側角色管理后,我們直接點擊初始化權限,來初始化基本的權限
3、角色還有個功能就是 為角色分配權限,所以 我們要添加 擴展權限 - 分配權限
好了,我們重新進入我們的系統,是不是列表出來了,相應的操作按鈕也都出現了
三、添加修改角色
添加修改保存這些在前面我們講的很詳細了,都是一個操作方法,我直接把代碼貼出來,有些注意的地方 我做了注釋

1 /// <summary> 2 /// 加載詳情 3 /// </summary> 4 /// <returns></returns> 5 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "Detail")] 6 public ActionResult Detail(int? id) 7 { 8 var _entity = new Domain.SYS_ROLE() { ISCUSTOM = false }; 9 10 if(id!=null && id>0) 11 { 12 _entity = RoleManage.Get(p => p.ID == id); 13 } 14 else 15 { 16 if(!string.IsNullOrEmpty(Request.QueryString["systemId"])) 17 { 18 _entity.FK_BELONGSYSTEM = Request.QueryString["systemId"]; 19 } 20 } 21 22 ViewData["Systemlist"] = this.SystemManage.LoadSystemInfo(CurrentUser.System_Id); 23 24 return View(_entity); 25 } 26 /// <summary> 27 /// 保存角色 28 /// </summary> 29 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "Add,Edit")] 30 public ActionResult Save(Domain.SYS_ROLE entity) 31 { 32 bool isEdit = false; 33 var json = new JsonHelper() { Msg = "保存成功", Status = "n" }; 34 try 35 { 36 if (entity != null) 37 { 38 //判斷角色名是否漢字 39 if (System.Text.RegularExpressions.Regex.IsMatch(entity.ROLENAME.Trim(), "^[\u4e00-\u9fa5]+$")) 40 { 41 if (entity.ROLENAME.Length > 36) 42 { 43 json.Msg = "角色名稱最多只能能包含36個漢字"; 44 return Json(json); 45 } 46 47 //添加 48 if (entity.ID <= 0) 49 { 50 entity.CREATEDATE = DateTime.Now; 51 entity.CREATEPERID = this.CurrentUser.Name; 52 entity.UPDATEDATE = DateTime.Now; 53 entity.UPDATEUSER = this.CurrentUser.Name; 54 } 55 else //修改 56 { 57 entity.UPDATEDATE = DateTime.Now; 58 entity.UPDATEUSER = this.CurrentUser.Name; 59 isEdit = true; 60 } 61 //判斷角色是否重名 62 if (!this.RoleManage.IsExist(p => p.ROLENAME == entity.ROLENAME && p.ID != entity.ID)) 63 { 64 if (isEdit) 65 { 66 //系統更換 刪除所有權限 67 var _entity = RoleManage.Get(p => p.ID == entity.ID); 68 if (_entity.FK_BELONGSYSTEM != entity.FK_BELONGSYSTEM) 69 { 70 RolePermissionManage.Delete(p => p.ROLEID == _entity.ID); 71 } 72 } 73 if (RoleManage.SaveOrUpdate(entity, isEdit)) 74 { 75 json.Status = "y"; 76 } 77 else 78 { 79 json.Msg = "保存失敗"; 80 } 81 } 82 else 83 { 84 json.Msg = "角色名" + entity.ROLENAME + "已被使用,請修改角色名稱再提交"; 85 } 86 87 } 88 else 89 { 90 json.Msg = "角色名稱只能包含漢字"; 91 } 92 93 } 94 else 95 { 96 json.Msg = "未找到需要保存的角色信息"; 97 } 98 if (isEdit) 99 { 100 WriteLog(Common.Enums.enumOperator.Edit, "修改用戶角色,結果:" + json.Msg, Common.Enums.enumLog4net.INFO); 101 } 102 else 103 { 104 WriteLog(Common.Enums.enumOperator.Add, "添加用戶角色,結果:" + json.Msg, Common.Enums.enumLog4net.INFO); 105 } 106 } 107 catch (Exception e) 108 { 109 json.Msg = "保存用戶角色發生內部錯誤!"; 110 WriteLog(Common.Enums.enumOperator.None, "保存用戶角色:", e); 111 } 112 return Json(json); 113 }
四、刪除角色
刪除的時候 我們首先還是要判斷一下 是否是超級管理員,超級管理員角色不允許刪除 然后我們要判斷用戶是否分配了角色

1 /// <summary> 2 /// 刪除角色 3 /// </summary> 4 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "Remove")] 5 public ActionResult Delete(string idList) 6 { 7 var json = new JsonHelper() { Msg = "刪除角色完畢", Status = "n" }; 8 var id = idList.Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToList(); 9 if (id.Contains(Common.Enums.ClsDic.DicRole["超級管理員"])) 10 { 11 json.Msg = "刪除失敗,不能刪除系統固有角色!"; 12 WriteLog(Common.Enums.enumOperator.Remove, "刪除用戶角色:" + json.Msg, Common.Enums.enumLog4net.ERROR); 13 return Json(json); 14 } 15 if (this.UserRoleManage.IsExist(p => id.Contains(p.FK_ROLEID))) 16 { 17 json.Msg = "刪除失敗,不能刪除系統中正在使用的角色!"; 18 WriteLog(Common.Enums.enumOperator.Remove, "刪除用戶角色:" + json.Msg, Common.Enums.enumLog4net.ERROR); 19 return Json(json); 20 } 21 try 22 { 23 //1、刪除角色權限 24 RolePermissionManage.Delete(p => id.Contains(p.ROLEID)); 25 //2、刪除角色 26 RoleManage.Delete(p => id.Contains(p.ID)); 27 json.Status = "y"; 28 WriteLog(Common.Enums.enumOperator.Remove, "刪除用戶角色:" + json.Msg, Common.Enums.enumLog4net.WARN); 29 } 30 catch (Exception e) 31 { 32 json.Msg = "刪除用戶角色發生內部錯誤!"; 33 WriteLog(Common.Enums.enumOperator.Remove, "刪除用戶角色:", e); 34 } 35 return Json(json); 36 }
五、分配權限
我們移步 權限控制器 PermissionController
1、我們新建個方法PerAllocation() 用戶角色分配權限 和 特殊用戶 分配權限
1 /// <summary> 2 /// 角色、用戶分配權限 3 /// </summary> 4 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "Allocation")] 5 public ActionResult PerAllocation() 6 {}
2、定義個變量systemId 輸出到前台,當前的系統名稱,如果沒有傳入系統ID 那就是用戶所有可操作的系統
1 //系統 2 string systemId = "所有可操作系統";
3、接收兩個參數 一個是 id(用戶或角色的ID) 另一個是 權限類型(用戶或角色)
1 //用戶或角色ID 2 string id = Request["id"]; 3 4 //權限類型,user/role 5 string tp = Request["tp"];
4、搜索關鍵字用於輸出給視圖展示
1 //搜索關鍵字 2 ViewBag.Search = base.keywords;
5、先判斷一下 權限類型 和 與用戶或角色 ID 是否為空
1 if (string.IsNullOrEmpty(tp)) 2 { 3 return Content("<script>alert('未接收到需要分配權限的類型')</script>"); 4 } 5 if (string.IsNullOrEmpty(id)) 6 { 7 return Content("<script>alert('未接收到需要分配權限的對象')</script>"); 8 }
6、獲取一下 系統下的模塊
1 int newid = int.Parse(id); 2 3 //模塊 4 var moduleList = new List<Domain.SYS_MODULE>(); 5 6 if (tp == "role") 7 { 8 var Role = RoleManage.Get(p => p.ID == newid); 9 10 systemId = SystemManage.Get(p => p.ID == Role.FK_BELONGSYSTEM.ToString()).NAME; 11 12 //獲取角色所屬系統模塊 13 moduleList = this.ModuleManage.RecursiveModule(this.ModuleManage.LoadAll(p => p.FK_BELONGSYSTEM == Role.FK_BELONGSYSTEM).ToList()); 14 } 15 else if (tp == "user") 16 { 17 //獲取管理員可操作系統模塊 18 moduleList = this.ModuleManage.RecursiveModule(this.ModuleManage.LoadAll(p => CurrentUser.System_Id.Any(e => e == p.FK_BELONGSYSTEM)).ToList()); 19 } 20 21 //搜索關鍵字 22 if (!string.IsNullOrEmpty(keywords)) 23 { 24 moduleList = moduleList.Where(p => p.NAME.Contains(keywords.ToLower())).ToList(); 25 } 26 27 ViewData["ModuleList"] = JsonConverter.JsonClass(moduleList.Select(p => new { p.ID, MODULENAME = GetModuleName(p.NAME, p.LEVELS), p.ICON, p.PARENTID, p.LEVELS }));
7、獲取模塊的所有可操作權限
1 //獲取權限 2 var moduleId = moduleList.Select(p => p.ID).ToList(); 3 4 ViewData["PermissionList"] = this.PermissionManage.LoadAll(p => moduleId.Any(e => e == p.MODULEID)).ToList();
8、根據類型獲取用戶/角色已選中的權限
1 //根據類型獲取用戶/角色已選中的權限 2 var selectper = new List<string>(); 3 if (tp == "user") 4 { 5 selectper = 6 this.UserPermissionManage.LoadAll(p => p.FK_USERID == newid) 7 .Select(p => p.FK_PERMISSIONID) 8 .Cast<string>() 9 .ToList(); 10 } 11 else if (tp == "role") 12 { 13 selectper = 14 this.RolePermissionManage.LoadAll(p => p.ROLEID == newid) 15 .Select(p => p.PERMISSIONID) 16 .Cast<string>() 17 .ToList(); 18 } 19 20 ViewData["selectper"] = selectper; 21 22 ViewData["PermissionType"] = tp; 23 24 ViewData["objId"] = id; 25 26 ViewData["systemId"] = systemId;
9、完整的代碼

1 /// <summary> 2 /// 角色、用戶分配權限 3 /// </summary> 4 [UserAuthorizeAttribute(ModuleAlias = "Role", OperaAction = "Allocation")] 5 public ActionResult PerAllocation() 6 { 7 //系統 8 string systemId = "所有可操作系統"; 9 //用戶或角色ID 10 string id = Request["id"]; 11 12 //權限類型,user/role 13 string tp = Request["tp"]; 14 15 //搜索關鍵字 16 ViewBag.Search = base.keywords; 17 18 if (string.IsNullOrEmpty(tp)) 19 { 20 return Content("<script>alert('未接收到需要分配權限的類型')</script>"); 21 } 22 if (string.IsNullOrEmpty(id)) 23 { 24 return Content("<script>alert('未接收到需要分配權限的對象')</script>"); 25 } 26 27 int newid = int.Parse(id); 28 29 //模塊 30 var moduleList = new List<Domain.SYS_MODULE>(); 31 32 if (tp == "role") 33 { 34 var Role = RoleManage.Get(p => p.ID == newid); 35 36 systemId = SystemManage.Get(p => p.ID == Role.FK_BELONGSYSTEM.ToString()).NAME; 37 38 //獲取角色所屬系統模塊 39 moduleList = this.ModuleManage.RecursiveModule(this.ModuleManage.LoadAll(p => p.FK_BELONGSYSTEM == Role.FK_BELONGSYSTEM).ToList()); 40 } 41 else if (tp == "user") 42 { 43 //獲取管理員可操作系統模塊 44 moduleList = this.ModuleManage.RecursiveModule(this.ModuleManage.LoadAll(p => CurrentUser.System_Id.Any(e => e == p.FK_BELONGSYSTEM)).ToList()); 45 } 46 47 //搜索關鍵字 48 if (!string.IsNullOrEmpty(keywords)) 49 { 50 moduleList = moduleList.Where(p => p.NAME.Contains(keywords.ToLower())).ToList(); 51 } 52 53 ViewData["ModuleList"] = JsonConverter.JsonClass(moduleList.Select(p => new { p.ID, MODULENAME = GetModuleName(p.NAME, p.LEVELS), p.ICON, p.PARENTID, p.LEVELS })); 54 55 //獲取權限 56 var moduleId = moduleList.Select(p => p.ID).ToList(); 57 58 ViewData["PermissionList"] = this.PermissionManage.LoadAll(p => moduleId.Any(e => e == p.MODULEID)).ToList(); 59 60 //根據類型獲取用戶/角色已選中的權限 61 var selectper = new List<string>(); 62 if (tp == "user") 63 { 64 selectper = 65 this.UserPermissionManage.LoadAll(p => p.FK_USERID == newid) 66 .Select(p => p.FK_PERMISSIONID) 67 .Cast<string>() 68 .ToList(); 69 } 70 else if (tp == "role") 71 { 72 selectper = 73 this.RolePermissionManage.LoadAll(p => p.ROLEID == newid) 74 .Select(p => p.PERMISSIONID) 75 .Cast<string>() 76 .ToList(); 77 } 78 79 ViewData["selectper"] = selectper; 80 81 ViewData["PermissionType"] = tp; 82 83 ViewData["objId"] = id; 84 85 ViewData["systemId"] = systemId; 86 87 return View(); 88 }
10、視圖頁代碼

1 @{ 2 Layout = "~/Views/Shared/_Layout.cshtml"; 3 } 4 <style type="text/css">.gray-bg {background-color: white;} 5 .permissionlist .icheck_line {color: #1ab394;cursor: pointer;font-weight:normal;margin-right:5px;} 6 </style> 7 <div class="wrapper wrapper-content animated fadeInUp"> 8 <div class="row"> 9 <div class="ibox-detail-title"> 10 <i class="fa fa-pencil-square-o"></i>分配權限 11 </div> 12 <div class="ibox-content"> 13 @using (Ajax.BeginForm("PerAllocation", null, new AjaxOptions() { }, new { @id = "form1", @class = "form-horizontal", @method = "get" })) 14 { 15 @Html.Hidden("tp", ViewData["PermissionType"]) 16 @Html.Hidden("id", ViewData["objId"]) 17 <div class="row"> 18 <div class="col-sm-6"> 19 <label>系統:</label> 20 <label class="icheck_line" style="color:#1ab394"> @ViewData["systemId"]</label> 21 </div> 22 <div class="col-sm-6"> 23 <div class="input-group"> 24 @Html.TextBox("Search", null, new { @class = "input-sm form-control", @placeholder = "請輸入查詢關鍵詞" }) 25 <span class="input-group-btn"> 26 <button type="submit" onclick="submit()" class="btn btn-sm btn-primary"> 搜索</button> 27 </span> 28 </div> 29 </div> 30 </div> 31 } 32 <div class="row"> 33 <table class="table table-striped table-bordered table-hover dataTables-example" style="text-align:center;"> 34 <thead> 35 <tr> 36 <th class="tn" style="width: 50px !important"><input name="checkall" class="icheck_box" type="checkbox" value=""></th> 37 <th style="width:200px!important;">模塊名稱</th> 38 <th>權限</th> 39 </tr> 40 </thead> 41 <tbody> 42 @{ 43 var module = ViewData["ModuleList"] as dynamic; 44 var permission = ViewData["PermissionList"] as List<Domain.SYS_PERMISSION>; 45 var selectper = ViewData["selectper"] as List<string>; 46 if (module != null) 47 { 48 foreach (var item in module) 49 { 50 <tr> 51 <td class="tn"> 52 @{ 53 if (permission.FindAll(p => p.MODULEID == item.ID).Count > 0) 54 { 55 <input name="ckb_module" class="icheck_box" type="checkbox" value="" data-id="@item.ID" /> 56 } 57 } 58 59 </td> 60 <td style="width:200px!important;text-align:left;"><a href="javascript:void(0)"><i class="@item.ICON"></i>@Html.Raw(item.MODULENAME)</a></td> 61 <td style="text-align:left;"> 62 <div class="permissionlist"> 63 @{ 64 if (permission != null && permission.Count > 0 && permission.FindAll(p => p.MODULEID == item.ID).Count > 0) 65 { 66 foreach (var per in permission.FindAll(p => p.MODULEID == item.ID)) 67 { 68 var sel = selectper.Find(p => p == per.ID.ToString()); 69 <label class="icheck_line"><input name="ckb_per" type="checkbox" data-module="@item.ID" class="icheck_box" value="@per.ID" @(sel != null ? "checked" : "") /><i class="@per.ICON"></i>@per.NAME</label> 70 } 71 } 72 } 73 </div> 74 </td> 75 </tr> 76 } 77 } 78 } 79 </tbody> 80 </table> 81 </div> 82 83 <div class="hr-line-dashed"></div> 84 <div class="text-center"> 85 <button class="btn btn-primary btn-save" type="submit"><i class="fa fa-check"></i> <span>確定保存</span></button> 86 <button class="btn btn-warning" id="btn-dig-close" type="button"><i class="fa fa-reply-all"></i> 取消返回</button> 87 </div> 88 </div> 89 </div> 90 </div> 91 @section scripts{ 92 <script type="text/javascript"> 93 $(function () { 94 //全選 反選 95 $('input[name="checkall"]').on('ifChecked', function (event) { 96 $("input[name='ckb_module']").iCheck('check'); 97 }); 98 $('input[name="checkall"]').on('ifUnchecked', function (event) { 99 $("input[name='ckb_module']").iCheck('uncheck'); 100 }); 101 //單行選中 取消 102 $('input[name="ckb_module"]').on('ifChecked', function (event) { 103 $("input[data-module='" + $(this).attr("data-id") + "']").iCheck('check'); 104 }); 105 $('input[name="ckb_module"]').on('ifUnchecked', function (event) { 106 $("input[data-module='" + $(this).attr("data-id") + "']").iCheck('uncheck'); 107 }); 108 //提交保存 109 $('.btn-save').click(function () { 110 var perid = ''; 111 $('input[name="ckb_per"]:checked').each(function () { 112 perid += $(this).attr('value') + ','; 113 }); 114 $.post('/Sys/Permission/SaveAllocation', { 115 tp: $('#tp').val(), 116 id: $('#id').val(), 117 perid: perid 118 }, function (result) { 119 if (result.Status == 'y') { 120 var dialog = top.dialog.get(window); 121 dig.successcallback(result.Msg, function () { 122 if (dialog == "undefined" || dialog == undefined) { 123 location.reload(); 124 } 125 else { 126 dialog.close('yes').remove(); 127 } 128 129 }); 130 } else { 131 dig.error(result.Msg); 132 } 133 }, 'json'); 134 }); 135 }); 136 </script> 137 }
11、保存用戶/角色 分配的權限
1 /// <summary> 2 /// 設置角色、用戶權限 3 /// </summary> 4 public ActionResult SaveAllocation() 5 { 6 var json = new JsonHelper(){Msg = "分配權限完畢",Status = "n"}; 7 //類型 8 string tp = Request.Form["tp"]; 9 //對象ID 10 string id = Request.Form["id"]; 11 //權限ID集合 12 string perid = Request.Form["perid"]; 13 14 if (string.IsNullOrEmpty(id)) 15 { 16 json.Msg = "未要分配權限的對象"; 17 WriteLog(Common.Enums.enumOperator.Allocation, "設置角色權限,結果:" + json.Msg, Common.Enums.enumLog4net.ERROR); 18 return Json(json); 19 } 20 21 if (string.IsNullOrEmpty(tp)) 22 { 23 json.Msg = "未要分配權限的類型"; 24 WriteLog(Common.Enums.enumOperator.Allocation, "設置角色權限,結果:" + json.Msg, Common.Enums.enumLog4net.ERROR); 25 return Json(json); 26 } 27 28 perid = perid.Trim(','); 29 30 try 31 { 32 if (tp == "user") 33 { 34 if (!this.UserPermissionManage.SetUserPermission(int.Parse(id), perid)) { json.Msg = "保存失敗"; WriteLog(Common.Enums.enumOperator.Allocation, "設置用戶權限,結果:" + json.Msg, Common.Enums.enumLog4net.ERROR); return Json(json); } 35 } 36 else if (tp == "role") 37 { 38 if (!this.RolePermissionManage.SetRolePermission(int.Parse(id), perid)) { json.Msg = "保存失敗"; WriteLog(Common.Enums.enumOperator.Allocation, "設置角色權限,結果:" + json.Msg, Common.Enums.enumLog4net.ERROR); return Json(json); } 39 } 40 41 json.Status = "y"; 42 43 WriteLog(Common.Enums.enumOperator.Allocation, "設置角色權限,結果:" + json.Msg, Common.Enums.enumLog4net.INFO); 44 } 45 catch (Exception e) 46 { 47 json.Msg = "設置角色權限發生內部錯誤!"; 48 WriteLog(Common.Enums.enumOperator.Allocation, "設置角色權限:", e); 49 } 50 return Json(json); 51 }
列表、添加、修改、刪除 這些操作 根據前面做的復制黏貼 然后稍微改一下 就OK了,是不是 做個功能 只要邏輯清晰 其實十分簡單、方便?
原創文章 轉載請尊重勞動成果 http://yuangang.cnblogs.com