mvc-百步飞剑-10
说明:权限管理-可直接对用户分配权限,也可通过给用户指定角色的方式分配权限.

1: 丰富Model类

2: 通过T4模板生成相应代码.T4模板的使用教程,在我的其他随笔(通过T4模板实现代码自动生成)中有介绍,对应的T4模板放置在百度网盘中的对应目录下
如果在序列化时报错,则做相应的修改.我运行时没有报错

3 添加角色管理
3.1 添加RoleInfoController控制器
using BBFJ.OA.Model; using BBFJ.OA.Model.EnumType; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BBFJ.OA.WebApp.Controllers { public class RoleInfoController : Controller { // // GET: /RoleInfo/ IBLL.IRoleInfoService RoleInfoService { get; set; } //别忘了在Config下的Controllers中添加新的控制器 public ActionResult Index() { return View(); } //获取角色列表 public ActionResult GetRoleInfoList() { int pageIndex = Request["page"] != null ? int.Parse(Request["page"]) : 1; int pageSize = Request["rows"] != null ? int.Parse(Request["rows"]) : 5; int totalCount; short delFlag = (short)DeleteEnumType.Normal; var roleInfoList = RoleInfoService.LoadPageEntities<int>(pageIndex, pageSize, out totalCount, r => r.DelFlag == delFlag, r => r.ID, true); var temp = from r in roleInfoList select new {ID=r.ID, RoleName=r.RoleName, Sort = r.Sort, Remark = r.Remark, SubTime =r.SubTime}; return Json(new { rows = temp,total = totalCount},JsonRequestBehavior.AllowGet); } //展示添加表单 public ActionResult ShowAddInfo() { return View(); } //完成角色信息的添加 public ActionResult AddRoleInfo(RoleInfo roleInfo) { roleInfo.ModifiedOn = DateTime.Now.ToString(); roleInfo.SubTime = DateTime.Now; roleInfo.DelFlag = 0; RoleInfoService.AddEntity(roleInfo); return Content("ok"); } } }
3.2 添加Index视图
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>角色管理</title> <link href="~/Content/themes/default/easyui.css" rel="stylesheet" /> <link href="~/Content/themes/icon.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.easyui.min.js"></script> <script src="~/Scripts/easyui-lang-zh_CN.js"></script> <script src="~/Scripts/datapattern.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script type="text/javascript"> $(function () { $("#addDiv").css("display","none"); loadData(); }) function loadData(pars) { $('#tt').datagrid({ url: '/RoleInfo/GetRoleInfoList', title: '角色数据表格', width: 700, height: 400, fitColumns: true, //列自适应 nowrap: false, idField: 'ID',//主键列的列明 loadMsg: '正在加载角色的信息...', pagination: true,//是否有分页 singleSelect: false,//是否单行选择 pageSize: 5,//页大小,一页多少条数据 pageNumber: 1,//当前页,默认的 pageList: [5, 10, 15], queryParams: pars,//往后台传递参数 columns: [[//c.UserName, c.UserPass, c.Email, c.RegTime { field: 'ck', checkbox: true, align: 'left', width: 50 }, { field: 'ID', title: '编号', width: 80 }, { field: 'RoleName', title: '角色姓名', width: 120 }, { field: 'Sort', title: '排序', width: 120 }, { field: 'Remark', title: '备注', width: 120 }, { field: 'SubTime', title: '时间', width: 80, align: 'right', formatter: function (value, row, index) { return (eval(value.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"))).pattern("yyyy-M-d"); } } ]], toolbar: [{ id: 'btnDelete', text: '删除', iconCls: 'icon-remove', handler: function () { deleteInfo(); } }, { id: 'btnAdd', text: '添加', iconCls: 'icon-add', handler: function () { addInfo(); } }, { id: 'btnEidt', text: '编辑', iconCls: 'icon-edit', handler: function () { showEditInfo(); } }], }); } //添加信息 function addInfo() { //给ifrme指定页面的urldizhi $("#addFrame").attr("src","/RoleInfo/ShowAddInfo"); //展示div $("#addDiv").css("display", "block"); $('#addDiv').dialog({ title: '添加角色数据', width: 300, height: 350, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //提交表单 //调用子窗体的方法 var childwindow = $("#addFrame")[0].contentWindow;//表示获取了嵌入在ifram中的子窗体对象 childwindow.subForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#addDiv').dialog('close'); } }] }); } //添加完成后调用该方法(子窗体调) function afterAdd(data) { if (data == "ok") { $('#addDiv').dialog('close'); $('#tt').datagrid('reload');//加载表格不会跳到第一页 } } </script> </head> <body> <div> <table id="tt" style="width: 700px;" title="标题,可以使用代码进行初始化,也可以使用这种属性的方式" iconcls="icon-edit"></table> </div> <!----------添加表单-----------> <div id="addDiv"> <iframe id="addFrame" width="100%" height="100%" frameborder="0"></iframe> </div> </body> </html>
3.3 在Config文件中做相应的添加
<?xml version="1.0" encoding="utf-8" ?> <objects> <object type="BBFJ.OA.BLL.UserInfoService, BBFJ.OA.BLL" singleton="false" name="userInfoService"> </object> <object type="BBFJ.OA.BLL.RoleInfoService, BBFJ.OA.BLL" singleton="false" name="roleInfoService"> </object> </objects>
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <!--控制器--> <object type="BBFJ.OA.WebApp.Controllers.UserInfoController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="UserInfoService" ref="userInfoService" /> </object> <object type="BBFJ.OA.WebApp.Controllers.LoginController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="UserInfoService" ref="userInfoService" /> </object> <object type="BBFJ.OA.WebApp.Controllers.RoleInfoController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="RoleInfoService" ref="roleInfoService" /> </object> <!--intentionally do NOT register the AccountController or the ValuesController with the container; demonstrates that the underlying default controller factory will properly (attempt to!) resolve all controllers not registered with Spring.NET using its default controller resolution behavoir--> <!--<object type="Spring.Mvc4QuickStart.Controllers.AccountController, Spring.Mvc4QuickStart" singleton="false" />--> <!--<object type="Spring.Mvc4QuickStart.Controllers.ValuesController, Spring.Mvc4QuickStart" singleton="false" />--> </objects>
3.4 创建添加信息的视图
@model BBFJ.OA.Model.RoleInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>添加角色</title> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> @*点击主窗体的按钮,调用子窗体的Ajax表单*@ <script type="text/javascript"> function subForm() { $("#addRoleForm").submit(); } function afterAdd(data) { //子窗体调用父窗体的方法 window.parent.afterAdd(data); } </script> </head> <body> @using (Ajax.BeginForm("AddRoleInfo", "RoleInfo", new { }, new AjaxOptions() { OnSuccess = "afterAdd" }, new { id="addRoleForm"})) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>RoleInfo</legend> <div class="editor-label"> @Html.LabelFor(model => model.RoleName) </div> <div class="editor-field"> @Html.EditorFor(model => model.RoleName) @Html.ValidationMessageFor(model => model.RoleName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remark) </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> <div class="editor-label"> @Html.LabelFor(model => model.Sort) </div> <div class="editor-field"> @Html.EditorFor(model => model.Sort) @Html.ValidationMessageFor(model => model.Sort) </div> </fieldset> } </body> </html>
这里值得一提的是子窗体和父窗体之间的相互调用.哎!老贴代码没什么意思,还是一步一步给大家讲一下吧.以给角色分配权限为例.
4 为角色分配权限.
4.1 步步解析/RoleInfo/Index
4.1.1 在角色管理父窗体上添加一个tab,为角色分配权限
{ id: 'btnSetRoleAction', text: '为角色分配权限', iconCls: 'icon-edit', handler: function () { setUserRole(); } }
4.1.2 当点击"为角色分配权限"按钮时,调用一个方法,使其弹出一个对话框,框中显示各种权限.这时候为了/RoleInfo/Index中的代码不那么冗杂,我们新建一个视图ShowRoleAction,用于存放分配角色的表单.现在问题是当用户点击"为角色分配权限"按钮时,如何调用视图ShowRoleAction
4.1.3 首先判断是否选中一行记录
var rows = $('#tt').datagrid('getSelections');//获取所选择的行
if ( rows.length != 1) {
$.messager.alert("提醒", "请选择一项角色!", "error");
return;
}
4.1.4 我们在父窗体RoleInfo/index中添加一个div,然后通过iframe关联一个页面.
<div id="setUserRoleDiv"> <iframe id="setRoleFrame" width="100%" height="100%" frameborder="0"></iframe> </div>
4.1.5 然后在function()设置其显示属性为隐藏
$("#setUserRoleDiv").css("display", "none");
4.1.6 当点击按钮时调用Tab中的 showRoleAction();方法使其显示.但是要注意先将要权限的信息嵌入到iframe中,然后显示div
4.1.6.1 指定具体页面的url地址,找到iframe并给相应的属性
$("#setRoleFrame").attr("src", "/UserInfo/SetUserRoleInfo/?id=" + rows[0].ID);
4.1.6.2 显示div
$("#setUserRoleDiv").css("display", "block");
4.1.6.3 以dialog的方式显示出来
function setUserRole() { var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if ( rows.length != 1) { //alert("请选择要修改的商品!"); $.messager.alert("提醒", "请选择要一项角色!", "error"); return; } $("#setUserRoleDiv").css("display", "block"); $("#setRoleFrame").attr("src", "/UserInfo/SetUserRoleInfo/?id=" + rows[0].ID); $("#setUserRoleDiv").dialog({ title: '为用户分配角色', width: 300, height: 400, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //提交表单 //调用子窗口的方法 var childWindow = $("#setRoleFrame")[0].contentWindow;//获取嵌入在iframe中的子窗体的window对象 childWindow.subEditForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#setUserRoleDiv').dialog('close'); } }] }); }
4.2 权限管理
4.2.1 要显示权限信息,所以添加权限信息控制器和视图,同时也要在Config中设置
using BBFJ.OA.BLL; using BBFJ.OA.Model.EnumType; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BBFJ.OA.WebApp.Controllers { public class ActionInfoController : BaseController { // // GET: /ActionInfo/ IBLL.IActionInfoService ActionInfoService { set;get;} public ActionResult Index() { return View(); } #region 获取权限信息 public ActionResult GetActionInfo() { int pageIndex = Request["page"] != null ? int.Parse(Request["page"]) : 1; int pageSize = Request["rows"] != null ? int.Parse(Request["rows"]) : 5; int totalCount; short delFlag = (short)DeleteEnumType.Normal; var actionInfoList = ActionInfoService.LoadPageEntities<int>(pageIndex, pageSize, out totalCount, r => r.DelFlag == delFlag, r => r.ID, true); var temp = from r in actionInfoList select new { ID = r.ID, ActionInfoName = r.ActionInfoName, Sort = r.Sort, Remark = r.Remark, SubTime = r.SubTime, ActionMethodName = r.ActionMethodName, ActionTypeEnum=r.ActionTypeEnum, HttpMethod = r.HttpMethod, Url=r.Url }; return Json(new { rows = temp, total = totalCount }, JsonRequestBehavior.AllowGet); } #endregion } }
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>用户管理</title> <link href="~/Content/themes/default/easyui.css" rel="stylesheet" /> <link href="~/Content/themes/icon.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.easyui.min.js"></script> <script src="~/Scripts/easyui-lang-zh_CN.js"></script> <script src="~/Scripts/datapattern.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script type="text/javascript"> $(function () { $("#addDiv").css("display", "none"); $("#editDiv").css("display", "none"); loadData(); }); function loadData(pars) { $('#tt').datagrid({ url: '/ActionInfo/GetActionInfo', title: '权限表格', width: 700, height: 285, fitColumns: true, //列自适应 nowrap: false, idField: 'ID',//主键列的列明 loadMsg: '正在加载权限信息...', pagination: true,//是否有分页 singleSelect: false,//是否单行选择 pageSize: 5,//页大小,一页多少条数据 pageNumber: 1,//当前页,默认的 pageList: [5, 10, 15], queryParams: pars,//往后台传递参数 columns: [[//c.UserName, c.UserPass, c.Email, c.RegTime { field: 'ck', checkbox: true, align: 'left', width: 50 }, { field: 'ID', title: '编号', width: 50 }, { field: 'ActionInfoName', title: '权限名称', width: 80 }, { field: 'Sort', title: '排序', width: 40 }, { field: 'Remark', title: '备注', width: 150 }, { field: 'Url', title: '请求地址', width: 120 }, { field: 'HttpMethod', title: '请求方式', width: 80 }, { field: 'ActionTypeEnum', title: '权限类型', width: 80 }, { field: 'SubTime', title: '时间', width: 80, align: 'right', formatter: function (value, row, index) { return (eval(value.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"))).pattern("yyyy-M-d"); } }, //添加操作栏 { field: 'Operator', title: '操作', width: 120, align: 'right', formatter: function (value, row, index) { var str = "<a href='javascript:void(0)'ids='" + row.ID + "' class='deleteLink'>删除</a>"; str += " <a href='javascript:void(0)' ids='" + row.ID + "' class='editLink'>修改</a>"; return str; } } ]], toolbar: [{ id: 'btnDelete', text: '删除', iconCls: 'icon-remove', handler: function () { deleteInfo(); } }, { id: 'btnAdd', text: '添加', iconCls: 'icon-add', handler: function () { addInfo(); } }, { id: 'btnEidt', text: '编辑', iconCls: 'icon-edit', handler: function () { showEditInfo(); } }, { id: 'btnSetRoleAction', text: '为角色分配权限', iconCls: 'icon-edit', handler: function () { setUserRole(); } } ], }); } //删除数据 function deleteInfo() { var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (!rows || rows.length == 0) { //alert("请选择要修改的商品!"); $.messager.alert("提醒", "请选择要删除的记录!", "error"); return; } $.messager.confirm("提示", "确定要删除数据吗", function (r) { if (r) { //获取要删除的记录的ID值。 var rowsLength = rows.length; var strId = ""; for (var i = 0; i < rowsLength; i++) { strId = strId + rows[i].ID + ",";//1,2,3, } //去掉最后一个逗号. strId = strId.substr(0, strId.length - 1); //将获取的要删除的记录的ID值发送到服务端. $.post("/UserInfo/DeleteUserInfo", { "strId": strId }, function (data) { if (data == "ok") { $('#tt').datagrid('reload');//加载表格不会跳到第一页。 //清除上次操作的历史的记录。 $('#tt').datagrid('clearSelections') } else { $.messager.alert("提醒", "删除记录失败!", "error"); } }); } }); } //添加数据 function addInfo() { $("#addDiv").css("display", "block"); $('#addDiv').dialog({ title: '添加用户数据', width: 300, height: 200, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //表单校验 validateInfo($("#addForm")); $("#addForm").submit();//提交表单 } }, { text: 'Cancel', handler: function () { $('#addDiv').dialog('close'); } }] }); } //完成添加后调用该方法 function afterAdd(data) { if (data == "ok") { $('#addDiv').dialog('close'); $('#tt').datagrid('reload');//加载表格不会跳到第一页。 $("#addForm input").val(""); } } //表单校验 function validateInfo(control) { control.validate({//表示对哪个form表单进行校验,获取form标签的id属性的值 rules: {//表示验证规则 UName: "required",//表示对哪个表单元素进行校验,要写具体的表单元素的name属性的值 Remark: { required: true }, UPwd: { required: true, minlength: 5 }, Sort: { required: true } }, messages: { UName: "请输入用户名", Remark: { required: "请输入备注" }, UPwd: { required: "请输入密码", minlength: jQuery.format("密码不能小于{0}个字 符") }, Sort: { required: "请输入排序" } } }); } //展示一下要修改的数据. function showEditInfo() { //判断一下用户是否选择了要修改的数据 var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (rows.length != 1) { $.messager.alert("提示", "请选择要修改的数据", "error"); return; } //将要修改的数据查询出来,显示到文本框中。 var id = rows[0].ID; $.post("/UserInfo/ShowEditInfo", { "id": id }, function (data) { $("#txtUName").val(data.UName); $("#txtUPwd").val(data.UPwd); $("#txtRemark").val(data.Remark); $("#txtSort").val(data.Sort); $("#txtSubTime").val(ChangeDateFormat(data.SubTime)); $("#txtDelFlag").val(data.DelFlag); $("#txtId").val(data.ID); }); $("#editDiv").css("display", "block"); $('#editDiv').dialog({ title: '编辑用户数据', width: 300, height: 200, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //表单校验 validateInfo($("#editForm")); $("#editForm").submit();//提交表单 } }, { text: 'Cancel', handler: function () { $('#editDiv').dialog('close'); } }] }); } //更新以后调用该方法. function afterEdit(data) { if (data == "ok") { $('#editDiv').dialog('close'); $('#tt').datagrid('reload');//加载表格不会跳到第一页。 } else { $.messager.alert("提示", "修改的数据失败", "error"); } } //将序列化成json格式后日期(毫秒数)转成日期格式 function ChangeDateFormat(cellval) { var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10)); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); return date.getFullYear() + "-" + month + "-" + currentDate; } //------------04为用户分配权限开始---------------// function setUserRole() { var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (rows.length != 1) { //alert("请选择要修改的商品!"); $.messager.alert("提醒", "请选择要一项角色!", "error"); return; } $("#setUserRoleDiv").css("display", "block"); $("#setRoleFrame").attr("src", "/UserInfo/SetUserRoleInfo/?id=" + rows[0].ID); $("#setUserRoleDiv").dialog({ title: '为用户分配角色', width: 300, height: 400, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //提交表单 //调用子窗口的方法 var childWindow = $("#setRoleFrame")[0].contentWindow;//获取嵌入在iframe中的子窗体的window对象 childWindow.subSetRoleForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#setUserRoleDiv').dialog('close'); } }] }); } //更新以后调用该方法. function afterSetUserRole(data) { if (data == "ok") { $('#setUserRoleDiv').dialog('close'); } else { $.messager.alert("提示", "用户角色分配失败", "error"); } } //------------04为用户分配权限结束---------------// </script> </head> <body> <div> <table id="tt" style="width: 700px;" title="标题,可以使用代码进行初始化,也可以使用这种属性的方式" iconcls="icon-edit"></table> </div> <!--------------添加数据----------------------> <div id="addDiv"> @using (Ajax.BeginForm("AddUserInfo", "UserInfo", new { }, new AjaxOptions() { HttpMethod = "post", OnSuccess = "afterAdd" }, new { id = "addForm" })) { <table> <tr><td>用户名</td><td><input type="text" name="UName" /></td></tr> <tr><td>密码</td><td><input type="password" name="UPwd" /></td></tr> <tr><td>备注</td><td><input type="text" name="Remark" /></td></tr> <tr><td>排序</td><td><input type="text" name="Sort" /></td></tr> </table> } </div> <!--------------修改数据----------------------> <div id="editDiv"> @using (Ajax.BeginForm("EditUserInfo", "UserInfo", new { }, new AjaxOptions() { HttpMethod = "post", OnSuccess = "afterEdit" }, new { id = "editForm" })) { <input type="hidden" name="ID" id="txtId" /> <input type="hidden" name="SubTime" id="txtSubTime" /> <input type="hidden" name="DelFlag" id="txtDelFlag" /> <table> <tr><td>用户名</td><td><input type="text" name="UName" id="txtUName" /></td></tr> <tr><td>密码</td><td><input type="text" name="UPwd" id="txtUPwd" /></td></tr> <tr><td>备注</td><td><input type="text" name="Remark" id="txtRemark" /></td></tr> <tr><td>排序</td><td><input type="text" name="Sort" id="txtSort" /></td></tr> </table> } </div> <!--为用户分配角色信息--> <div id="setUserRoleDiv"> <iframe id="setRoleFrame" width="100%" height="100%" frameborder="0"></iframe> </div> </body> </html>
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <!--控制器--> <object type="BBFJ.OA.WebApp.Controllers.UserInfoController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="UserInfoService" ref="userInfoService" /> <property name="RoleInfoService" ref="roleInfoService" /> </object> <object type="BBFJ.OA.WebApp.Controllers.LoginController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="UserInfoService" ref="userInfoService" /> </object> <object type="BBFJ.OA.WebApp.Controllers.RoleInfoController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="RoleInfoService" ref="roleInfoService" /> </object> <object type="BBFJ.OA.WebApp.Controllers.ActionInfoController, BBFJ.OA.WebApp" singleton="false" > <!--控制器的属性--> <property name="ActionInfoService" ref="actionInfoService" /> </object> <!--intentionally do NOT register the AccountController or the ValuesController with the container; demonstrates that the underlying default controller factory will properly (attempt to!) resolve all controllers not registered with Spring.NET using its default controller resolution behavoir--> <!--<object type="Spring.Mvc4QuickStart.Controllers.AccountController, Spring.Mvc4QuickStart" singleton="false" />--> <!--<object type="Spring.Mvc4QuickStart.Controllers.ValuesController, Spring.Mvc4QuickStart" singleton="false" />--> </objects>
<?xml version="1.0" encoding="utf-8" ?> <objects> <object type="BBFJ.OA.BLL.UserInfoService, BBFJ.OA.BLL" singleton="false" name="userInfoService"> </object> <object type="BBFJ.OA.BLL.RoleInfoService, BBFJ.OA.BLL" singleton="false" name="roleInfoService"> </object> <object type="BBFJ.OA.BLL.ActionInfoService, BBFJ.OA.BLL" singleton="false" name="actionInfoService"> </object> </objects>

4.2.2 新增权限

注意两个地方:1:当选择菜单权限时,会有上传图标功能
<tr><td>权限类型</td><td>
<select name="ActionTypeEnum" id="selectActionType">
<option value="0">普通权限</option>
<option value="1">菜单权限</option>
</select>
</td></tr>
<tr style="display:none" id="imageIconTr">
<td>菜单图标</td><td><input type="file" name="MenuIcon" id="imgICon'"/><br /><input type="button" id="btnUpload" value="异步上传"/></td>
</tr>
$(function () { $("#addDiv").css("display", "none"); $("#editDiv").css("display", "none"); loadData(); //给权限类型下拉框加上改变事件 bindselectActionTypeChange(); }); function bindselectActionTypeChange() { $("#selectActionType").change(function () { if ($(this).val() == "0") { //如果选择了"普通权限" -- 隐藏菜单图标 $("#imageIconTr").fadeOut("slow"); } else { $("#imageIconTr").fadeIn("slow"); } }); }
2:异步上传,引用MyAjaxForm.js文件
<tr style="display:none" id="imageIconTr"> <td>菜单图标</td><td><input type="file" name="MenuIcon" id="imgICon'"/><br /><input type="button" id="btnUpload" value="异步上传"/> <input type="hidden" id="hidImage" name="MenuIcon" /> <div id="menuIconShow"> </div> </td> </tr>
//文件异步上传 function bindFileUpload() { $("#btnUpload").click(function () { if ($("#imgICon").val() == "") { $.messager.alert("提示", "请选择图片文件"); return; } $("#addDiv form").ajaxSubmit({ type: 'post', url: '/ActionInfo/GetMenuIcon', success: function (data) { var serverData = data.split(':'); if (serverData[0] == "ok") { $("#menuIconShow").append("<img src='" + serverData[1] + "' width='40px' height='40px'>"); //将服务端返回的图片路径赋值给隐藏域 $("#hidImage").attr("value", serverData[1]); } else { $.messager.alert("提示","图片上传错误!"); } } }); });

4.2.3 修改权限
4.2.3.1 在控制器中添加强类型视图
@model BBFJ.OA.Model.ActionInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>ShowEditInfo</title> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> <script type="text/javascript"> function subEditForm() { $("#form1").submit(); } function afterEdit(data) { window.parent.afterEdit(data); } </script> </head> <body> @using (Ajax.BeginForm("EditInfo", new { }, new AjaxOptions() { OnSuccess = "afterEdit" }, new { id = "form1" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>ActionInfo</legend> @Html.HiddenFor(model => model.ID) <div class="editor-label"> @Html.LabelFor(model => model.SubTime) </div> <div class="editor-field"> @Html.EditorFor(model => model.SubTime) @Html.ValidationMessageFor(model => model.SubTime) </div> <div class="editor-label"> @Html.LabelFor(model => model.DelFlag) </div> <div class="editor-field"> @Html.EditorFor(model => model.DelFlag) @Html.ValidationMessageFor(model => model.DelFlag) </div> <div class="editor-label"> @Html.LabelFor(model => model.ModifiedOn) </div> <div class="editor-field"> @Html.EditorFor(model => model.ModifiedOn) @Html.ValidationMessageFor(model => model.ModifiedOn) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remark) </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> <div class="editor-label"> @Html.LabelFor(model => model.Url) </div> <div class="editor-field"> @Html.EditorFor(model => model.Url) @Html.ValidationMessageFor(model => model.Url) </div> <div class="editor-label"> @Html.LabelFor(model => model.HttpMethod) </div> <div class="editor-field"> @Html.EditorFor(model => model.HttpMethod) @Html.ValidationMessageFor(model => model.HttpMethod) </div> <div class="editor-label"> @Html.LabelFor(model => model.ActionMethodName) </div> <div class="editor-field"> @Html.EditorFor(model => model.ActionMethodName) @Html.ValidationMessageFor(model => model.ActionMethodName) </div> <div class="editor-label"> @Html.LabelFor(model => model.ControllerName) </div> <div class="editor-field"> @Html.EditorFor(model => model.ControllerName) @Html.ValidationMessageFor(model => model.ControllerName) </div> <div class="editor-label"> @Html.LabelFor(model => model.ActionInfoName) </div> <div class="editor-field"> @Html.EditorFor(model => model.ActionInfoName) @Html.ValidationMessageFor(model => model.ActionInfoName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Sort) </div> <div class="editor-field"> @Html.EditorFor(model => model.Sort) @Html.ValidationMessageFor(model => model.Sort) </div> <div class="editor-label"> @Html.LabelFor(model => model.ActionTypeEnum) </div> <div class="editor-field"> @*@Html.EditorFor(model => model.ActionTypeEnum)*@ <select name="ActionTypeEnum"> @if (Model.ActionTypeEnum == 0) { <option value="0" selected="selected">普通权限</option> <option value="1" >菜单权限</option> } else { <option value="0" >普通权限</option> <option value="1" selected="selected">菜单权限</option> } </select> @Html.ValidationMessageFor(model => model.ActionTypeEnum) </div> <div class="editor-label"> @Html.LabelFor(model => model.MenuIcon) </div> <div class="editor-field"> @Html.EditorFor(model => model.MenuIcon) @Html.ValidationMessageFor(model => model.MenuIcon) </div> <div class="editor-label"> @Html.LabelFor(model => model.IconWidth) </div> <div class="editor-field"> @Html.EditorFor(model => model.IconWidth) @Html.ValidationMessageFor(model => model.IconWidth) </div> <div class="editor-label"> @Html.LabelFor(model => model.IconHeight) </div> <div class="editor-field"> @Html.EditorFor(model => model.IconHeight) @Html.ValidationMessageFor(model => model.IconHeight) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> </body> </html>
//展示一下要修改的数据. function showEditInfo() { //判断一下用户是否选择了要修改的数据 var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (rows.length != 1) { $.messager.alert("提示", "请选择要修改的数据", "error"); return; } //将要修改的数据查询出来,显示到文本框中。 $("#editDiv").css("display", "block"); $("#editFrame").attr("src","/ActionInfo/ShowEditInfo/?id="+rows[0].ID); $('#editDiv').dialog({ title: '编辑权限数据', width: 300, height: 400, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //提交表单 //调用子窗口的方法 var childWindow = $("#editFrame")[0].contentWindow;//获取嵌入在iframe中的子窗体的window对象 childWindow.subEditForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#editDiv').dialog('close'); } }] }); } //更新以后调用该方法. function afterEdit(data) { if (data == "ok") { $('#editDiv').dialog('close'); $('#tt').datagrid('reload');//加载表格不会跳到第一页。 } else { $.messager.alert("提示", "修改的数据失败", "error"); } }
#region 04显示要修改的权限信息 public ActionResult ShowEditInfo() { int id = int.Parse(Request["id"]); ViewData.Model =ActionInfoService.LoadEntities(a=>a.ID == id).FirstOrDefault(); return View(); } #endregion #region 05-保存-编辑好的权限信息 public ActionResult EditInfo(ActionInfo actionInfo) { ActionInfoService.EditEntity(actionInfo); return Content("ok"); } #endregion

4.3 为权限分配角色
4.3.1 Index中的修改
{ id: 'btnSetRoleAction', text: '为权限分配角色', iconCls: 'icon-edit', handler: function () { setActionRoleInfo(); }
<!--为权限分配角色信息-->
<div id="setActionRoleDiv">
<iframe id="setActionRoleFrame" width="100%" height="100%" frameborder="0"></iframe>
</div>
function setActionRoleInfo() { var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (rows.length != 1) { $.messager.alert("提醒", "请选择要一项权限!", "error"); return; } $("#setActionRoleDiv").css("display", "block"); $("#setActionRoleFrame").attr("src", "/ActionInfo/SetActionRoleInfo/?id=" + rows[0].ID); $("#setActionRoleDiv").dialog({ title: '为权限分配角色', width: 300, height: 400, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //提交表单 //调用子窗口的方法 var childWindow = $("#setActionRoleFrame")[0].contentWindow;//获取嵌入在iframe中的子窗体的window对象 childWindow.subSetRoleForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#setActionRoleDiv').dialog('close'); } }] }); } //更新以后调用该方法. function afterSetActionRole(data) { if (data == "ok") { $('#setActionRoleDiv').dialog('close'); } else { $.messager.alert("提示", "用户权限分配失败", "error"); } }
4.3.2 在控制器中写方法,然后添加视图
#region 06给权限分配角色信息 public ActionResult SetActionRoleInfo() { //01获取权限编号 int id =int.Parse(Request["id"]); //02根据权限编号-查询权限信息 var actionInfo = ActionInfoService.LoadEntities(a=>a.ID == id).FirstOrDefault(); ViewBag.ActionInfo = actionInfo; short DelFlag = (short)DeleteEnumType.Normal; ViewBag.AllRoles = RoleInfoService.LoadEntities(r=>r.DelFlag == DelFlag).ToList(); //查询出当前权限已经有的角色 ViewBag.AllExtRoleIds = (from r in actionInfo.RoleInfo select r.ID).ToList(); return View(); } [HttpPost] public ActionResult SetActionRoleInfo(FormCollection collection) { int actionId = int.Parse(Request["actionId"]); string[] Allkeys = Request.Form.AllKeys; List<int> list = new List<int>(); foreach (string key in Allkeys) { if (key.StartsWith("cba_")) { string k = key.Replace("cba_", ""); list.Add(int.Parse(k)); } } ActionInfoService.SetActionRoleInfo(actionId,list); return Content("ok"); } #endregion
4.3.3 在视图中修改代码
@{ Layout = null; } @using BBFJ.OA.Model; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>为权限分配角色</title> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> <script type="text/javascript"> function subSetRoleForm() { $("#form1").submit(); } function afterSetRole(data) { window.parent.afterSetActionRole(data); } </script> </head> <body> <div> 为权限 @{ ActionInfo actionInfo = (ActionInfo)ViewBag.ActionInfo; <span style="font-size:16px;color:red">@actionInfo.ActionInfoName</span> }分配角色 </div> <div> @using(Ajax.BeginForm("SetActionRoleInfo",new{},new AjaxOptions(){OnSuccess="afterSetRole",HttpMethod="post" },new{id ="form1"})) { <input type="hidden" name="actionId" value="@actionInfo.ID" /> List<RoleInfo> AllRoleList =(List<RoleInfo>)ViewBag.AllRoles; List<int> RoleIdList = (List<int>)ViewBag.AllExtRoleIds; foreach (var roleInfo in AllRoleList) { var name = "cba_" +roleInfo.ID; if (RoleIdList.Contains(roleInfo.ID)) { <input type="checkbox" checked="checked" name="@name" value ="@roleInfo.ID"/>@roleInfo.RoleName } else { <input type="checkbox" name="@name" value="@roleInfo.ID" />@roleInfo.RoleName } } } </div> </body> </html>


浙公网安备 33010602011771号