Lintway-春暖花开-01权限管理练习
1 用户管理模板
主要通过angularjs实现了用的增删改以及列表的显示和分页
1.1 添加功能,点击”添加用户”按钮,显示出添加用户的div

1.2 展示功能,每页显示数据数目为5条,当数据过多时候有分页显示功能,

1.3 修改功能,点击”修改”链接,打开修改页面,并把本条数据显示到与之对应的文本框中,同时做一些简单的非空验证
1.4 删除功能,点击删除,给出删除确认框,确定后通过逻辑删除,删除数据
1.5 分配角色.点击”分配角色”链接,打开”角色列表”,如果用户已经具有该角色,会在角色前面的选中框中自动选择,如果该用户不具有某一角色,可以通过勾选角色前面的文本框为其分配角色


@{ Layout = null; } <!doctype html> <html ng-app="UserInfo_Index"> <head> <meta charset="utf-8"> <title>用户管理</title> <script src="~/Scripts/angular.min.js"></script> <script src="~/Scripts/js/UserInfo.js?version=<%=VersionNo %>"></script> <link href="~/Style/weibo.css" rel="stylesheet" /> <link href="~/Style/main.css" rel="stylesheet" /> </head> <body ng-controller="UserInfo"> <a href="javascript:;" ng-click="showAddDivForAdd()">添加用户</a> <table class="items-listing"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>备注</th> <th>操作</th> </tr> </thead> <tbody> <tr ng-repeat="userInfo in userInfoList"> <td><a href="#/ProductEdit?code={{userInfo.ID}}">{{userInfo.ID}}</a></td> <td>{{userInfo.UserName}}</td> <td>{{userInfo.Remark}}</td> <td><a href="javascript:;" ng-click="del(userInfo.ID)">删除</a> <a href="javascript:;" ng-click="modify(userInfo.ID)">修改</a> <a href="javascript:;" ng-click="getUserRoleList(userInfo.ID)">分配角色</a></td> </tr> </tbody> </table> <!--------------页码条--开始--------------------> <div class="page"> <a href="javascript:;" ng-repeat="page in pages" class="{{page.className}}" ng-click="changePage(page.num)">{{page.num}}</a> </div> <!--------------页码条--结束--------------------> <!--------------添加数据--开始--------------------> <div id="addDiv" ng-show="addDivIsShow"> <table class="addDiv"> <tr><td>用户名</td><td><input type="text" name="UserName" ng-model="txtUserName" /></td></tr> <tr><td>密码</td><td><input type="password" name="UserPwd" ng-model="txtUserPwd" /></td></tr> <tr><td>备注</td><td><input type="text" name="Remark" ng-model="txtRemark" /></td></tr> <tr><td><input type="button" class="inputs" value="保存" ng-click="submitMsg()" /></td><td><input type="button" class="inputs" value="取消" ng-click="addDivIsShow=false" /></td></tr> </table> @*TODO:表单中name属性值 === 实体类中属性名称,可以传递一个实体,使用MVC的自动填充功能*@ </div> <!--------------添加数据--结束--------------------> <!--------------为用户分配角色信息--------------------> <div id="setUserRoleDiv" ng-show="userRoleDivIsShow"> <table class="items-listing"> <thead> <tr> <td> <input type="checkbox" ng-model="allCheck" ng-click="allChecked()" /></td> <th>ID</th> <th>角色名称</th> <th>备注</th> @*<th>是否是该角色</th>*@ </tr> </thead> <tbody> <tr ng-repeat="userRole in userRoleList"> <td><input type="checkbox" ng-model="userRole.State" ng-click="itemCheck()" /></td> <td> {{userRole.ID}} </td> <td>{{userRole.RoleName}}</td> <td>{{userRole.Remark}}</td> <tr><td><input type="button" class="inputs" value="保存" ng-click="setUserRoleList()" /></td><td><input type="button" class="inputs" value="取消" ng-click="userRoleDivIsShow=false" /></td></tr> </tbody> </table> <!--------------页码条--开始--------------------> <div class="page"> <a href="javascript:;" ng-repeat="page in pagesUserRole" class="{{page.className}}" ng-click="changePageUserRole(page.num)">{{page.num}}</a> </div> <!--------------页码条--开始--------------------> </div> </body> </html>
var app = angular.module('UserInfo_Index', []); app.controller('UserInfo', function ($scope, $http) { $scope.userInfoList = []; //用户信息数据 $scope.addDivIsShow = false;//设置添加用户的div是否隐藏 $scope.hidID = "";//设置 用户的ID 如果ID不为空表示修改数据,否则,表示添加数据 $scope.pages = [];//定义页码 $scope.curPage = 1;//定义当前页码 $scope.total = 0;//定义总条数 $scope.countPage = 1;//定义总页数 $scope.pageSize = 5;//定义每页包含的数目;一般通过后台配置或者webconfig $scope.roleInfoList = []; //角色信息数据 $scope.userRoleDivIsShow = false;//设置添加用户的div是否隐藏 $scope.pagesUserRole = [];//定义页码 $scope.curPageUserRole = 1;//定义当前页码 $scope.totalUserRole = 0;//定义总条数 $scope.countPageUserRole = 1;//定义总页数 $scope.pageSizeUserRole = 5;//定义每页包含的数目;一般通过后台配置或者webconfig //加载页面 getUserInfoList($scope.curPage); //获取用户列表 List function getUserInfoList(currentIndex) { $http.get('/UserInfo/getList', { params: { pageSize: $scope.pageSize, pageIndex: currentIndex } }).success(function (strResult) { $scope.userInfoList = strResult.rows; $scope.total = strResult.total; $scope.countPage = strResult.countPage; setCurrentPage(); }).error(function () { alert('错误,请联系管理员'); }); } //点击添加按钮,显示添加div $scope.showAddDivForAdd = function () { //1:显示修改的div $scope.addDivIsShow = true; //2:清空div中的值 $scope.hidID =""; $scope.txtUserName = ""; $scope.txtUserPwd =""; $scope.txtRemark = ""; } //新增+修改 二合一 $scope.submitMsg = function () { $http.get('/UserInfo/ModifyUserInfo', { params: { ID: $scope.hidID, UserName: $scope.txtUserName, UserPwd: $scope.txtUserPwd, Remark: $scope.txtRemark } }).success(function (strResult) { if (strResult != null && strResult.result == "ok") { alert('成功了'); //刷新页面,通过unshift把最新的是数据放置在最上面 $scope.userInfoList.unshift(strResult.rows[0]); //修改成功后重新加载页面 getUserInfoList($scope.curPage); $scope.addDivIsShow = false; } else { alert('失败' + strResult.detail); } }).error(function () { //TODO:这里有一个bug,就是修改以后会报500错误 // alert('错误,请联系管理员!'); getUserInfoList($scope.curPage); $scope.addDivIsShow = false; }); } //删除 $scope.del = function (id) { if (confirm("确认要删除?")) { $http.get('/UserInfo/DeleteUserInfo', { params: { act:"del",strId: id } }).success(function (strResult) { if (strResult != null && strResult.result == "ok") { getUserInfoList($scope.curPage); alert('删除成功'); } else { alert('删除失败'); } }).error(function () { alert('错误,请联系管理员!'); }); } } //修改 $scope.modify = function (id) { var userInfo = {}; for (var i = 0; i < $scope.userInfoList.length; i++) { if ($scope.userInfoList[i].ID == id) { userInfo = $scope.userInfoList[i]; } } if (userInfo != null) { //1:显示修改的div $scope.addDivIsShow = true; //2:给div中的内容赋值 $scope.hidID = userInfo.ID; $scope.txtUserName=userInfo.UserName; $scope.txtUserPwd = userInfo.UserPwd; $scope.txtRemark = userInfo.Remark; } } //页码--开始 $scope.changePage = function (curPage) { $scope.curPage = curPage; getUserInfoList(curPage); } //将函数放到$scope上,方便ng-click使用 $scope.getUserInfoList = getUserInfoList; function setCurrentPage() { $scope.pages = [];//先清空一下 for (var i = 1; i <= $scope.countPage; i++) { if (i == $scope.curPage) { $scope.pages.push({ num: i, className: 'active' }); } else { $scope.pages.push({ num: i, className: '' }); } } } //页码--结束 //------------04为用户分配权限开始---------------// //全选 $scope.allCheck = false; $scope.allChecked = function () { for (var i = 0; i < $scope.userRoleList.length; i++) { if ($scope.allCheck === true) { $scope.userRoleList[i].State = true; } else { $scope.userRoleList[i].State = false; } } }; //如果选项全部现在 全选按键自动为true $scope.itemCheck = function () { var flag = 0; for (var i = 0; i < $scope.userRoleList.length; i++) { if ($scope.userRoleList[i].State == true) { flag++; } } if (flag == $scope.userRoleList.length) { $scope.allCheck = true; } else { $scope.allCheck = false; } }; function setCurrentPageUserRole() { $scope.pagesUserRole = [];//先清空一下 for (var i = 1; i <= $scope.countPageUserRole; i++) { if (i == $scope.curPageUserRole) { $scope.pagesUserRole.push({ num: i, className: 'active' }); } else { $scope.pagesUserRole.push({ num: i, className: '' }); } } } //页码 $scope.changePageUserRole = function (curPage) { $scope.curPageUserRole = curPage; getUserRoleList(curPage); } //获取用户列表 List function getUserRoleList(id) { $scope.userRoleDivIsShow = true;//设置添加用户的div显示 $scope.hidID = id; //点击"编辑权限"的时候,获取到被编辑人的userID $http.get('/UserInfo/GetUserRoleInfo', { params: { pageSize: $scope.pageSize, pageIndex: $scope.currentIndexUserRole, strId: id } }).success(function (strResult) { console.log(strResult.rows); $scope.userRoleList = strResult.rows; $scope.totalUserRole = strResult.total; $scope.countPageUserRole = strResult.countPage; setCurrentPageUserRole(); }).error(function () { alert('错误,请联系管理员'); }); } $scope.getUserRoleList = getUserRoleList; //设置用户角色. $scope.setUserRoleList = function setUserRoleList() { var strIds = ""; for (var i = 0; i < $scope.userRoleList.length; i++) { if ($scope.userRoleList[i].State == true) { strIds = strIds + $scope.userRoleList[i].ID + ";"; } } $http.get('/UserInfo/SetUserRoleInfo', { //传递userID,被分配权限的ID; 被分配的角色 params: { userID: $scope.hidID, roleIDs: strIds } }).success(function (strResult) { console.log(strResult.rows); $scope.userRoleList = strResult.rows; $scope.totalUserRole = strResult.total; // $scope.countPageUserRole = strResult.countPage; }).error(function () { alert('错误,请联系管理员'); }); //关闭窗口 $scope.userRoleDivIsShow = false; } //------------04为用户分配权限结束---------------// });
using Lintway.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Lintway.WebApp.Controllers { public class UserInfoController : Controller { // // GET: /UserInfo/ IBLL.IUserInfoService UserInfoService = new BLL.UserInfoService(); IBLL.IRoleInfoService RoleInfoService = new BLL.RoleInfoService(); public ActionResult Index() { return View(); } /// <summary> /// 获取用户列表 /// </summary> /// <returns></returns> public ActionResult getList() { int pageIndex = 1; string pageIndexStr = Request["pageIndex"]; int.TryParse(pageIndexStr, out pageIndex); int pageSize = 5; int totalCount; double countPage = 1; short delFlag = (short)DeleteEnumType.Normal; try { var userInfoList = UserInfoService.LoadPageEntities<int>(pageIndex, pageSize, out totalCount, c => c.DelFlag == delFlag, c => c.ID, false); //将数据生成json返回表格 var temp = from u in userInfoList select new { ID = u.ID, UserName = u.UserName, SubTime = u.SubTime, Remark = u.Remark }; //返回总的记录数和数据 countPage = Math.Ceiling(totalCount / (double)pageSize); return Json(new { rows = temp, total = totalCount, countPage = countPage }, JsonRequestBehavior.AllowGet); } catch (Exception) { throw; } } /// <summary> /// 添加用户 /// </summary> /// <returns></returns> public ActionResult ModifyUserInfo(UserInfo userInfo) { string strID = Request["ID"]; int id = 0; if (!String.IsNullOrWhiteSpace(strID) && int.TryParse(strID, out id)) { userInfo = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault(); } string userName = Request["UserName"]; string userPWD = Request["UserPwd"]; if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(userPWD)) { return Json(new { result = "error", detail = "用户名或密码为空" }, JsonRequestBehavior.AllowGet); } userInfo.UserName = userName; userInfo.UserPwd = userPWD; userInfo.Remark = Request["Remark"]; userInfo.DelFlag = 0; userInfo.SubTime = DateTime.Now; if (id > 0) { UserInfoService.EditEntity(userInfo); } else { UserInfoService.AddEntity(userInfo); } return Json(new { result = "ok", rows = userInfo }, JsonRequestBehavior.AllowGet); } /// <summary> /// 删除用户(硬删除)--一般不使用 /// </summary> /// <returns></returns> public ActionResult DeleteUserInfoYing(string strId) { strId = Request["strId"]; int id = 0; if (int.TryParse(strId, out id)) { UserInfo userInfoList = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault(); if (userInfoList != null && UserInfoService.DeleteEntity(userInfoList)) { return Content("ok"); } else { return Content("no"); } } else { return Content("no"); } } /// <summary> /// (软删除)-- /// </summary> /// <returns></returns> public ActionResult DeleteUserInfo(string strId) { strId = Request["strId"]; int id = 0; if (int.TryParse(strId, out id)) { UserInfo userInfoList = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault(); if (userInfoList != null) { //添加一个枚举,统一管理 userInfoList.DelFlag = (short)DeleteEnumType.LogicDelete; if (UserInfoService.EditEntity(userInfoList)) { return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet); } else { return Json(new { result = "error", detail = "数据删除失败!" }, JsonRequestBehavior.AllowGet); } } else { return Json(new { result = "error", detail = "该用户不存在或已删除!" }, JsonRequestBehavior.AllowGet); } } else { return Json(new { result = "error", detailInfo = "传递的用户ID不正确,请联系管理员!" }, JsonRequestBehavior.AllowGet); } } #region 获取用户分配角色 public ActionResult GetUserRoleInfo() { int pageIndex = 1; string pageIndexStr = Request["pageIndex"]; int.TryParse(pageIndexStr, out pageIndex); pageIndex = pageIndex < 1 ? 1 : pageIndex; int pageSize = 5; int totalCount; double countPage = 1; short delFlag = (short)DeleteEnumType.Normal; try { var roleInfoList = RoleInfoService.LoadPageEntities<int>(pageIndex, pageSize, out totalCount, c => c.DelFlag == delFlag, c => c.ID, false); if (roleInfoList.FirstOrDefault() == null) { return Json(new { result = "error", detail = "请先添加角色" }, JsonRequestBehavior.AllowGet); } int id = int.Parse(Request["strId"]); //先获取要当前用户信息 var userInfoList = UserInfoService.LoadEntities(r => r.ID == id); //将数据生成json返回表格 var temp = from r in roleInfoList select new { ID = r.ID, RoleName = r.RoleName, SubTime = r.SubTime, Remark = r.Remark, State = r.UserInfo.Where(u => u.ID == id).Count() > 0 ? true : false }; //返回总的记录数和数据 countPage = Math.Ceiling(totalCount / (double)pageSize); return Json(new { rows = temp, total = totalCount, countPage = countPage }, JsonRequestBehavior.AllowGet); } catch (Exception) { throw; } } #endregion #region 设置用户分配角色 public ActionResult SetUserRoleInfo() { string userIDStr = Request["userID"]; string roleIDsStr = Request["roleIDs"]; int id = 0; if (!String.IsNullOrWhiteSpace(userIDStr) && int.TryParse(userIDStr, out id)) { var userInfo = UserInfoService.LoadEntities(u => u.ID == id).FirstOrDefault(); if (userInfo != null) { //先删除该用户角色 userInfo.RoleInfo.Clear(); //userInfo.RoleInfo = null; //保存用户信息 UserInfoService.EditEntity(userInfo); if (roleIDsStr!="") { List<RoleInfo> roleInfoList=new List<RoleInfo>(); string[] roleArrayStr = roleIDsStr.Split(';'); int count = roleArrayStr.Length; for (int i = 0; i < count; i++) { int roleID = 0; if (int.TryParse(roleArrayStr[i],out roleID)) { RoleInfo curRoleInfo = RoleInfoService.LoadEntities(u => u.ID == roleID).FirstOrDefault(); if (curRoleInfo!=null) { roleInfoList.Add(curRoleInfo); } } } //为该用户设置角色 userInfo.RoleInfo = roleInfoList; //保存用户信息 UserInfoService.EditEntity(userInfo); } } return Json(new { result = "error", detail = "该用户不存在或已被删除" }, JsonRequestBehavior.AllowGet); } else { return Json(new { result="error",detail="请先选择被分配的用户"}, JsonRequestBehavior.AllowGet); } } #endregion } }
2 角色管理模块
主要通过jQuery-easyUI实现了用的增删改以及列表的显示和分页
2.1 添加功能,点击”添加”按钮

2.2 展示功能,可以设置每页显示数据数目,当数据过多时候有分页显示功能,

2.3 修改功能,点击”编辑”按钮,弹出修改对话框,并把本条数据显示到与之对应的文本框中

2.4 删除功能,点击删除,给出删除确认框,确定后通过逻辑删除,支持批量删除

2.5 为角色分配权限. 点击”为角色分配权限”按钮,打开”权限列表”,如果角色已经具有该权限,会在权限前面的选中框中自动选择,如果该角色不具有某一权限,可以通过勾选权限前面的文本框为其分配权限

using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using Lintway.Model; namespace Lintway.WebApp.Controllers { public class RoleInfoController : Controller { // // GET: /RoleInfo/ IBLL.IRoleInfoService RoleInfoService = new BLL.RoleInfoService(); IBLL.IActionInfoService ActionInfoService = new BLL.ActionInfoService(); //别忘了在Config下的Controllers中添加新的控制器 public ActionResult Index() { return View(); } #region 01获取角色列表 //获取角色列表 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; try { 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, Remark = r.Remark, SubTime = r.SubTime }; return Json(new { rows = temp, total = totalCount }, JsonRequestBehavior.AllowGet); } catch (Exception) { throw; } } #endregion #region 02-1展示添加表单 //展示添加表单 public ActionResult ShowAddInfo() { return View(); } #endregion #region 02-2添加角色 //完成角色信息的添加 public ActionResult AddRoleInfo(RoleInfo roleInfo) { roleInfo.SubTime = DateTime.Now; roleInfo.DelFlag = 0; RoleInfoService.AddEntity(roleInfo); return Content("ok"); } #endregion #region 03-删除角色 public ActionResult DeleteRoleInfo() { string strId = Request["strId"]; string[] strIds = strId.Split(','); List<int> list = new List<int>(); foreach (string id in strIds) { list.Add(int.Parse(id)); } try { RoleInfoService.DeleteEntities(list);//批量删除 return Content("ok"); } catch (Exception) { throw; } } #endregion #region 04-显示-要编辑角色信息 public ActionResult ShowEditAction() { int id = int.Parse(Request["id"]); ViewData.Model = RoleInfoService.LoadEntities(r => r.ID == id).FirstOrDefault(); return View(); } #endregion #region 05-保存-编辑好的角色信息 public ActionResult EditInfo(RoleInfo roleInfo) { //加上这句 roleInfo.SubTime = DateTime.Now; RoleInfoService.EditEntity(roleInfo); return Content("ok"); } #endregion #region 06 为角色分配权限 public ActionResult SetRoleActionInfo() { try { int id = int.Parse(Request["id"]); //先获取要当前角色信息 var roleInfo = RoleInfoService.LoadEntities(r => r.ID == id).FirstOrDefault(); ViewBag.RoleInfo = roleInfo; short DelFlag = (short)DeleteEnumType.Normal; //显示所有的权限名称 ViewBag.AllActions = ActionInfoService.LoadEntities(r => r.DelFlag == DelFlag).ToList(); //////////------查看角色已经具有什么权限开始------////////// ViewBag.AllExtActionIds = (from r in roleInfo.ActionInfo select r.ID).ToList(); //////////------查看角色已经具有什么权限结束------////////// return View(); } catch (Exception) { throw; } } #endregion #region 07-为角色分配权限 [HttpPost] public ActionResult SetRoleActionInfo(FormCollection collection) { int roleId = int.Parse(Request["roleId"]); //获取表单的值 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)); } } RoleInfoService.SetRoleAction(roleId, list); return Content("ok"); } #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"); $("#setRoleActionDiv").css("display", "none"); loadData(); }) function loadData(pars) { $('#tt').datagrid({ url: '/RoleInfo/GetRoleInfoList', title: '角色数据表格', width: 700, height: 300, 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: '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 () { showEditAction(); } }, { id: 'btnSetRoleAction', text: '为角色分配权限', iconCls: 'icon-edit', handler: function () { setRoleAction(); } } ], onLoadSuccess: function (e, field) { $(".deleteLink").bind("click", function () { //alert($(this).attr("ids")); deleteInfo(); }); } }); } //------------01添加信息开始---------------// //添加信息 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');//加载表格不会跳到第一页 } } //------------01添加信息结束---------------// //------------02修改信息开始---------------// //02修改信息开始 function showEditAction() { //判断一下用户是否选择了一个角色 var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (rows.length != 1) { $.messager.alert("提示", "请选择要修改的角色", "error"); return; } //指定iframe的src $("#editFrame").attr("src", "/RoleInfo/ShowEditAction/?id=" + rows[0].ID); $("#editDiv").css("display", "block"); $("#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.subSetActionForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#editDiv').dialog('close'); } }] }); } //更新以后调用该方法. function afterEdit(data) { if (data == "ok") { $('#editDiv').dialog('close'); $('#tt').datagrid('reload');//加载表格不会跳到第一页。 } else { $.messager.alert("提示", "修改的数据失败", "error"); } } //------------02修改信息结束---------------// //------------03删除信息开始---------------// 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("/RoleInfo/DeleteRoleInfo", { "strId": strId }, function (data) { if (data == "ok") { $('#tt').datagrid('reload');//加载表格不会跳到第一页。 //清除上次操作的历史的记录。 $('#tt').datagrid('clearSelections') } else { $.messager.alert("提醒", "删除记录失败!", "error"); } }); } }); } //------------03删除信息结束---------------// //------------04为角色分配权限开始---------------// //当点击"为角色分配权限"按钮时,调用一个方法,弹出一个对话框,框中显示各种权限,为了使本页面中的代码不那么冗杂 //新建一个视图ShowRoleAction,用于窜访分配权限的表单 function setRoleAction() { var rows = $('#tt').datagrid('getSelections');//获取所选择的行 if (rows.length != 1) { $.messager.alert("提醒", "请选择要一项角色!", "error"); return; } $("#setRoleActionDiv").css("display", "block"); $("#setActionFrame").attr("src", "/RoleInfo/SetRoleActionInfo/?id=" + rows[0].ID); $("#setRoleActionDiv").dialog({ title: '为角色分配权限', width: 300, height: 400, collapsible: true, maximizable: true, resizable: true, modal: true, buttons: [{ text: 'Ok', iconCls: 'icon-ok', handler: function () { //提交表单 //调用子窗口的方法 var childWindow = $("#setActionFrame")[0].contentWindow;//获取嵌入在iframe中的子窗体的window对象 childWindow.subSetActionForm();//调用子窗体中的方法,完成表单提交 } }, { text: 'Cancel', handler: function () { $('#setRoleActionDiv').dialog('close'); } }] }); } //更新以后调用该方法. function afterSetRoleAction(data) { if (data == "ok") { $('#setRoleActionDiv').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"> <iframe id="addFrame" width="100%" height="100%" frameborder="0"></iframe> </div> <!----------修改表单-----------> <div id="editDiv"> <iframe id="editFrame" width="100%" height="100%" frameborder="0"></iframe> </div> <!--为角色分配权限信息--> @*在父窗体中添加一个div,然后通过iframe关联一个页面*@ <div id="setRoleActionDiv"> <iframe id="setActionFrame" width="100%" height="100%" frameborder="0"></iframe> </div> </body> </html>
@{ Layout = null; } @using Lintway.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 subSetActionForm() { $("#form1").submit(); } function afterSetRoleAction(data) { //调用父窗体中的方法 window.parent.afterSetRoleAction(data); } </script> </head> <body> <div> 为角色 @{ RoleInfo roleInfo = (RoleInfo)ViewBag.RoleInfo; <span style="font-size:18px;color:red">@roleInfo.RoleName</span> } 分配权限 @{ using (Ajax.BeginForm("SetRoleActionInfo", new { }, new AjaxOptions() { OnSuccess = "afterSetRoleAction", HttpMethod = "post" }, new { id = "form1" })) { //提交表单的同时将角色编号提交.SetRoleActionInfo方法拿到角色ID后就知道给那个角色分配权限了 <input type="hidden" name="roleId" value="@roleInfo.ID" /> //隐藏域 List<ActionInfo> actionInfoList = (List<ActionInfo>)ViewBag.AllActions; //所有权限 List<int> ExtActionIdList = (List<int>)ViewBag.AllExtActionIds; //角色已经具有的权限 foreach (var actionInfo in actionInfoList) { //创建文本框 string actionName = "cba_" + actionInfo.ID; //判断角色是否具有此权限 if (ExtActionIdList.Contains(actionInfo.ID)) { <input type="checkbox" name="@actionName" value="@actionInfo.ID" checked="checked" />@actionInfo.ActionInfoName } else { <input type="checkbox" name="@actionName" value="@actionInfo.ID" />@actionInfo.ActionInfoName } } } } </div> </body> </html>
@model Lintway.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>角色管理</legend> <div class="editor-label"> 角色名称 </div> <div class="editor-field"> @Html.EditorFor(model => model.RoleName) @Html.ValidationMessageFor(model => model.RoleName) </div> <div class="editor-label"> 备注 </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> </fieldset> } </body> </html>
@model Lintway.Model.RoleInfo @{ Layout = null; } @using Lintway.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 subSetActionForm() { $("#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>角色信息</legend> @Html.HiddenFor(model => model.ID) <div class="editor-label"> 角色名称 </div> <div class="editor-field"> @Html.EditorFor(model => model.RoleName) @Html.ValidationMessageFor(model => model.RoleName) </div> <div class="editor-label"> 备注 </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> </fieldset> } </body> </html>
3 权限管理模块
主要通过Razor视图引擎 实现了用的增删改以及列表的显示功能
3.1添加功能,点击”添加权限”链接,跳转到新的页面

3.2修改功能,点击”编辑”链接,打开新页面,并把本条数据显示到与之对应的文本框中

3.3删除功能

@model IEnumerable<Lintway.Model.ActionInfo> @{ ViewBag.Title = "Index"; } <h2>权限管理</h2> <link href="~/Style/weibo.css" rel="stylesheet" /> <link href="~/Style/main.css" rel="stylesheet" /> <p> @Html.ActionLink("添加权限", "Create") </p> <table class="items-listing"> <tr> <th> 权限名称 </th> <th> 操作时间 </th> <th> 是否有效 </th> <th> 备注 </th> <th> 操作 </th> </tr> @foreach (var item in Model) { if (item.DelFlag==1) { continue; } <tr> <td> @Html.DisplayFor(modelItem => item.ActionInfoName) </td> <td> @Convert.ToDateTime(@Html.DisplayFor(modelItem => item.SubTime).ToString()).ToString("yyyy-MM-dd") </td> <td> @if (@Html.DisplayFor(modelItem => item.DelFlag).ToString() == "0") { @Html.Raw("有"); } else { @Html.Raw("无"); } </td> <td> @Html.DisplayFor(modelItem => item.Remark) </td> <td> @Html.ActionLink("编辑", "Edit", new { id = item.ID }) | @Html.ActionLink("删除", "Del", new { id = item.ID }) </td> </tr> } </table>
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using Lintway.Model; namespace Lintway.WebApp.Controllers { public class ActionInfoController : Controller { private LintwayEntities db = new LintwayEntities(); // // GET: /ActionInfo/ public ActionResult Index() { return View(db.ActionInfo.ToList()); } // // GET: /ActionInfo/Create public ActionResult Create() { return View(); } // // POST: /ActionInfo/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ActionInfo actioninfo) { if (ModelState.IsValid) { actioninfo.SubTime = DateTime.Now; actioninfo.DelFlag = 0; db.ActionInfo.Add(actioninfo); db.SaveChanges(); return RedirectToAction("Index"); } return View(actioninfo); } // // GET: /ActionInfo/Edit/5 public ActionResult Edit(int id = 0) { ActionInfo actioninfo = db.ActionInfo.Find(id); if (actioninfo == null) { return HttpNotFound(); } return View(actioninfo); } // // POST: /ActionInfo/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(ActionInfo actioninfo) { if (ModelState.IsValid) { actioninfo.SubTime = DateTime.Now; actioninfo.DelFlag = 0; db.Entry(actioninfo).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(actioninfo); } // // GET: /ActionInfo/Delete/5 public ActionResult Delete(int id = 0) { ActionInfo actioninfo = db.ActionInfo.Find(id); if (actioninfo == null) { return HttpNotFound(); } return View(actioninfo); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } public ActionResult Del(int id = 0) { ActionInfo actioninfo = db.ActionInfo.Find(id); actioninfo.DelFlag = 1; if (actioninfo == null) { return HttpNotFound(); } db.Entry(actioninfo).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Del(ActionInfo actioninfo) { if (ModelState.IsValid) { actioninfo.DelFlag = 1; db.Entry(actioninfo).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(actioninfo); } } }
@model Lintway.Model.ActionInfo @{ ViewBag.Title = "Create"; } <h2>新增</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <div class="editor-label"> </div> <div class="editor-field"> 权限名称: @Html.EditorFor(model => model.ActionInfoName) @Html.ValidationMessageFor(model => model.ActionInfoName) </div> <div class="editor-field"> 备注: @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> <p> <input type="submit" value="新增" /> </p> </fieldset> } <div> @Html.ActionLink("返回列表", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model Lintway.Model.ActionInfo @{ ViewBag.Title = "Edit"; } <h2>编辑</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>编辑权限</legend> @Html.HiddenFor(model => model.ID) <div class="editor-label"> 权限名称 </div> <div class="editor-field"> @Html.EditorFor(model => model.ActionInfoName) @Html.ValidationMessageFor(model => model.ActionInfoName) </div> <div class="editor-label"> 备注 </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> <p> <input type="submit" value="保存" /> </p> </fieldset> } <div> @Html.ActionLink("返回列表", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

浙公网安备 33010602011771号