【无私分享:从入门到精通ASP.NET MVC】从0开始,一起搭框架、做项目(9) 角色管理,分配权限

索引

【无私分享:从入门到精通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         }
View Code

 

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 }
View Code

 

二、添加模块和权限

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         }
View Code

 

四、删除角色 

删除的时候 我们首先还是要判断一下 是否是超级管理员,超级管理员角色不允许删除 然后我们要判断用户是否分配了角色

 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         }
View Code

 

五、分配权限

我们移步 权限控制器 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         }
View Code

 

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 }
View Code

 

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

 

posted @ 2016-06-08 11:30  果冻布丁喜之郎  阅读(49745)  评论(35编辑  收藏  举报