Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理7
做完角色之后接下来做先做页面按钮的增加、删除、修改。这里用到的功能和角色那边是一样的。就不多说了。直接上代码。
后台控制器代码
using AuthorDesign.Web.App_Start.Common; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AuthorDesign.Web.Areas.Admin.Controllers { public class PageActionController : Controller { // // GET: /Admin/PageAction/ public ActionResult PageActionList() { ViewBag.Title = "页面按钮列表"; return View(); } /// <summary> /// 获取列表 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public JsonResult PageActionList(Models.ButtonParamModel model) { int rowCount = 0; var result = EnterRepository.GetRepositoryEnter().GetPageActionRepository.LoadPageList(model.iDisplayStart, model.iDisplayLength, model.IsDesc, out rowCount); return Json(new { sEcho = model.sEcho, iTotalRecords = rowCount, iTotalDisplayRecords = rowCount, aaData = result }, JsonRequestBehavior.AllowGet); } /// <summary> /// 获取按钮信息 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpPost] public JsonResult GetPageActionInfo(int id = 0) { var result = EnterRepository.GetRepositoryEnter().GetPageActionRepository.LoadEntities(m => m.Id == id).FirstOrDefault(); if (result == null) { return Json(new { state = "error", message = "按钮不存在" }); } else { return Json(new { state = "success", result }); } } /// <summary> /// 添加页面按钮 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public JsonResult AddPageAction(Models.PageActionModel model) { if (ModelState.IsValid) { IDAL.IPageActionRepository pageActionRepository = EnterRepository.GetRepositoryEnter().GetPageActionRepository; //判断页面按钮代码是否已存在 var result = pageActionRepository.LoadEntities(m => m.ActionCode == model.ActionCode.Trim()).FirstOrDefault(); if (result == null) { pageActionRepository.AddEntity(new Model.PageAction() { ActionCode = model.ActionCode, ActionLevel = model.ActionLevel, IsShow = model.IsShow, Name = model.Name }); //添加下操作记录 PublicFunction.AddOperation(1, string.Format("添加页面按钮"), string.Format("添加角色=={0}==页面按钮成功", model.Name)); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "添加页面按钮成功" }); } else { PublicFunction.AddOperation(1, string.Format("添加页面按钮"), string.Format("添加页面按钮=={0}==失败", model.Name)); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "添加页面按钮失败" }); } } else { return Json(new { state = "error", message = "页面按钮代码已经存在了" }); } } else { return Json(new { state = "error", message = "信息不完整" }); } } /// <summary> /// 修改页面按钮 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public JsonResult UpdatePageAction(Models.PageActionModel model) { if (ModelState.IsValid && model.Id > 0) { IDAL.IPageActionRepository pageActionRepository = EnterRepository.GetRepositoryEnter().GetPageActionRepository; //判断权限名称是否已存在 var result = pageActionRepository.LoadEntities(m => m.ActionCode == model.ActionCode.Trim()).FirstOrDefault(); if (result != null && result.Id != model.Id) { return Json(new { state = "error", message = "页面按钮代码已经存在了" }); } else { Model.PageAction pageAction = new Model.PageAction() { ActionCode = model.ActionCode, ActionLevel = model.ActionLevel, IsShow = model.IsShow, Name = model.Name, Id = model.Id }; pageActionRepository.Get(m => m.Id == model.Id); pageActionRepository.EditEntity(pageAction, new string[] { "ActionCode", "ActionLevel", "IsShow", "Name" }); PublicFunction.AddOperation(1, string.Format("修改页面按钮"), string.Format("修改页面按钮=={0}==成功", model.Name)); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "修改页面按钮成功" }); } else { PublicFunction.AddOperation(1, string.Format("修改页面按钮"), string.Format("修改页面按钮=={0}==失败", model.Name)); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "修改页面按钮失败" }); } } } else { return Json(new { state = "error", message = "信息不完整" }); } } /// <summary> /// 更改按钮状态 /// </summary> /// <param name="id">按钮Id</param> /// <param name="state">按钮状态</param> /// <returns></returns> [HttpPost] public JsonResult UpdateState(int id = 0, int state = 0) { EnterRepository.GetRepositoryEnter().GetPageActionRepository.EditEntity(new Model.PageAction() { Id = id, IsShow = (byte)state }, new string[] { "IsShow" }); PublicFunction.AddOperation(1, string.Format("修改按钮状态"), string.Format("修改按钮状态成功")); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "修改按钮状态成功" }); } else { PublicFunction.AddOperation(1, string.Format("修改按钮状态"), string.Format("修改按钮状态失败")); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "服务器泡妞去了" }); } } } }
页面代码
@section Header{ <style type="text/css"> /*加载动态图片*/ .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 100%; height: 40px; margin-left: -50%; margin-top: -25px; padding-top: 20px; text-align: center; font-size: 1.2em; /*background-color: white;*/ } </style> } <div class="main-content"> <div class="breadcrumbs" id="breadcrumbs"> <script type="text/javascript"> try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { } </script> <ul class="breadcrumb"> <li> <i class="icon-home home-icon"></i> <a href="/Admin/Home">首页</a> </li> <li> <a href="/Admin/PageAction/PageActionList">页面按钮列表</a> </li> <li class="active">页面按钮列表</li> </ul><!-- .breadcrumb --> <!-- #nav-search --> </div> <div class="page-content"> <div class="row"> <div class="col-xs-12"> <!-- PAGE CONTENT BEGINS --> <div class="row"> <div class="col-xs-12"> <div class="table-header"> 页面按钮列表查看 </div> <div class="hidden" id="hidden_filter"> @* 把需要搜索的条件放到hidden里面,在table格式化完成的时候直接调用$.html()赋值,免去了在js拼接标签的麻烦 *@ <div style="float:left;"> <label class="AddRole"> <a id="AddNewButton" class="btn btn-xs btn-primary" data-toggle="modal" href="" onclick="showAddNewAdmin()" title="添加新按钮"> <i class="icon-plus-sign bigger-130"></i> 添加新按钮 </a> </label> </div> </div> <div class="table-responsive dataTables_wrapper"> <table id="sample-table-2" class="table table-striped table-bordered table-hover"> <thead> <tr> <th class="center sorting_disabled" role="columnheader" rowspan="1" colspan="1" aria-label="" style="width: 58px;"> <label> <input type="checkbox" class="ace"> <span class="lbl"></span> </label> </th> <th>动作名称</th> <th>动作代码</th> <th>是否显示</th> <th>动作等级</th> <th style="width: 120px;"> 操作 </th> </tr> </thead> </table> </div> </div> </div> <!-- PAGE CONTENT ENDS --> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.page-content --> </div> <div class="modal fade" id="ShowAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> @RenderPage("/Areas/Admin/Views/PageAction/DisplayTemplates/PageAction.cshtml") </div> @section script{ <script src="/Content/assets/js/jquery.dataTables.min.js"></script> <script src="/Content/assets/js/jquery.dataTables.bootstrap.js"></script> <script src="/Content/assets/js/bootbox.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <script type="text/javascript"> var isSearch = false; $(function () { var objTable = $("#sample-table-2").dataTable({ aoColumns: [ { "sClass": "center", "mDataProp": "Id", "bSortable": false }, { "sClass": "center", "mDataProp": "Name", "bSortable": false }, { "sClass": "center", "mDataProp": "ActionCode", "bSortable": false }, { "sClass": "center", "mDataProp": "IsShow", "bSortable": false }, { "mDataProp": "ActionLevel", "sClass": "center", "bSortable": true, "asSorting": ["asc", "desc"] }, { "sClass": "center", "mDataProp": "Id", "bSortable": false } ], "bServerSide": true,//分页,取数据等等的都放到服务端去 "bProcessing": true,//载入数据的时候是否显示“载入中” "aLengthMenu": [30, 50, 100], "bLengthChange": true, //改变每页显示数据数量 //"bFilter": false, //过滤功能 "iDisplayStart": 0, "iDisplayLength": 30,//首次加载的数据条数 "bStorable": true,//排序操作在服务端进行,所以可以关了。 "sAjaxSource": "/Admin/PageAction/PageActionList", "fnServerParams": function (aoData, bStorable) { }, /*如果加上下面这段内容,则使用post方式传递数据*/ "fnServerData": function (sSource, aoData, fnCallback, bStorable) { var paramList = { "sEcho": 0, "iDisplayLength": 0, "iDisplayStart": 0, "isDesc": bStorable.aaSorting[0][1] == "desc" ? true : false }; if (bStorable.aaSorting[0][0] == 0) { paramList.isDesc = true; } for (var i = 0; i < aoData.length; i++) { if (aoData[i].name == "iDisplayStart") { paramList.iDisplayStart = aoData[i].value; } else if (aoData[i].name == "iDisplayLength") { paramList.iDisplayLength = aoData[i].value; } else if (aoData[i].name == "sEcho") { paramList.sEcho = aoData[i].value; } } $.ajax({ "dataType": 'json', "type": "POST", "url": sSource, "data": paramList, "success": function (resp) { fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式 } }); }, "oLanguage": { "sSearch": "搜索", "sLengthMenu": "每页显示 _MENU_ 条记录", "sZeroRecords": "抱歉, 没有找到", "sInfo": "从 _START_ 到 _END_ 共 _TOTAL_ 条数据", "sInfoEmpty": "没有数据", "sInfoFiltered": "(从 _MAX_ 条数据中检索)", "oPaginate": { "sFirst": "首页", "sPrevious": "前一页", "sNext": "后一页", "sLast": "尾页" }, "sZeroRecords": "没有检索到数据", "sProcessing": "<img src='/Content/assets/images/loading.gif' />" }, "fnRowCallback": function (nRow, aData, iDisplayIndex) { /* 用来改写指定行的样式 */ $('td:eq(0)', nRow).html("<label><input type=\"checkbox\" class=\"ace\" value=\"" + aData.Id + "\"><span class=\"lbl\"></span></label>"); var html = "<div class=\"visible-md visible-lg hidden-sm hidden-xs action-buttons\">"; html += "<a class=\"green LookRole\" href=\"javascript:UpdateObj('" + aData.Id + "')\" title=\"编辑\"><i class=\"icon-pencil bigger-130\"></i></a>";//编辑 if (aData.IsShow == 0) { html += "<a class=\"green UpdateRole\" href=\"javascript:CanShow('" + aData.Id + "',1)\" title=\"设置显示\"><i class=\"icon-ok bigger-130\"></i></a>"; $('td:eq(3)', nRow).html("<i class=\"icon-remove red bigger-120\"></i>"); } else { html += "<a class=\"red UpdateRole\" href=\"javascript:CanShow('" + aData.Id + "',0)\" title=\"设置不显示\"><i class=\"icon-remove bigger-130\"></i></a>";//删除 $('td:eq(3)', nRow).html("<i class=\"icon-ok green bigger-120\"></i>"); } html += "</div>"; $('td:eq(5)', nRow).html(html); return nRow; } }); //下面的代码主要是将下拉框的位置已到右边去 $("#sample-table-2_length").parents().first().removeClass("col-sm-6").addClass("col-sm-3"); $("#sample-table-2_length").parents().first().css("float", "right"); $("#sample-table-2_filter").parents().first().removeClass("col-sm-6").addClass("col-sm-8"); $("#sample-table-2_filter").parents().first().css("float", "left"); $("#sample-table-2_length").css("float", "right"); $("#sample-table-2_filter").html($("#hidden_filter").html()); $("#hidden_filter").remove(); }) function showAddNewAdmin() { $("#Id").val(0); $('#ShowAdd').modal(); } function UpdateObj(id) { $.ajax({ type: "post", data: { id: id }, url: "/Admin/PageAction/GetPageActionInfo", success: function (result) { if (result.state == "success") { $("#Id").val(id); $("#Name").val(result.result.Name); $("#ActionCode").val(result.result.ActionCode); $("#ActionLevel").val(result.result.ActionLevel); if (result.result.IsShow == 0) { $("input[name='IsShow']").eq(0).removeAttr("checked"); $("input[name='IsShow']").eq(1).attr("checked", "checked"); } else { $("input[name='IsShow']").eq(0).attr("checked", "checked"); $("input[name='IsShow']").eq(1).removeAttr("checked"); } $('#ShowAdd').modal(); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) } $("#AddRoleForm").submit(function () { if ($("#AddRoleForm").valid()) { var url = "/Admin/PageAction/AddPageAction"; if ($("#Id").val() > 0) { url = "/Admin/PageAction/UpdatePageAction"; } $.ajax({ type: "post", data: $("#AddRoleForm").serialize(), url: url, success: function (result) { if (result.state == "success") { $('#ShowAdd').modal('hide');//关闭模态框 document.getElementById("AddRoleForm").reset();//清空表单 bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 }, message: result.message }); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) return false; } else { return false; } }) function CanShow(id, state) { bootbox.confirm({ buttons: { confirm: { label: '确定', className: 'btn-primary' }, cancel: { label: '取消', className: 'btn-default' } }, message: state == 0 ? "确定该按钮不显示吗" : "确定该按钮显示吗", callback: function (result) { if (result) { UpdateState(id, state) } } }); } function UpdateState(id, state) { $.ajax({ type: "post", data: { id: id, state: state }, url: "/Admin/PageAction/UpdateState", success: function (result) { if (result.state == "success") { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 }, message: result.message }); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) } </script> } @model AuthorDesign.Web.Areas.Admin.Models.PageActionModel <div class="main-content col-xs-8" style="margin-top: 70px; margin-left: 15%;"> <div class="page-content"> <div class="row"> <section> <div class="page-header"> <h1> 管理 <small> <i class="icon-double-angle-right"></i> <span id="ShowText">页面按钮编辑</span> </small> </h1> </div> <div class="col-lg-10 col-lg-offset-2"> <form id="AddRoleForm" class="form-horizontal"> <fieldset> @Html.HiddenFor(m => m.Id) <div class="form-group"> <label class="col-lg-3 control-label">按钮名称<span style="color:red;">*</span>:</label> <div class="col-lg-7" style="float:left;"> @Html.TextBoxFor(m => m.Name, new { @class = "col-sm-8" }) @Html.ValidationMessageFor(m => m.Name) </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">按钮代码<span style="color:red;">*</span>:</label> <div class="col-lg-7"> @Html.TextBoxFor(m => m.ActionCode, new { @class = "col-sm-8" }) @Html.ValidationMessageFor(m => m.ActionCode) </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">动作等级:</label> <div class="col-lg-7"> @Html.TextBoxFor(m => m.ActionLevel, new { @class = "col-sm-8" }) @Html.ValidationMessageFor(m => m.ActionLevel) </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">是否显示</label> <div class="col-lg-7"> <label> <input name="IsShow" type="radio" class="ace" value="1" checked="checked" /> <span class="lbl">显示</span> </label> <label> <input name="IsShow" type="radio" class="ace" value="0" /> <span class="lbl">不显示</span> </label> </div> </div> </fieldset> <div class="form-group"> <div class="col-lg-9 col-lg-offset-3"> <button class="btn btn-primary UpdateRole" type="submit"> <i class="icon-ok bigger-110"></i> 保存 </button> <button class="btn" type="reset" data-dismiss="modal"> <i class="icon-undo bigger-110"></i> 取消 </button> </div> </div> </form> </div> </section> <!-- /.row --> </div> </div> <!-- /.page-content --> </div>
页面执行效果
做完页面按钮的时候本来想先去做页面的增删改查的,但是发现页面的样式有点难找,就先弄了管理员的增加修改删除
首先也是控制器的代码
using AuthorDesign.Common; using AuthorDesign.Web.App_Start.Common; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AuthorDesign.Web.Areas.Admin.Controllers { public class AdminController : Controller { // // GET: /Admin/Admin/ public ActionResult AdminList() { ViewBag.Title = "管理员列表"; ViewBag.RoleSelectItem = SelectItemHelper.GetRoleItemList(0); return View(); } [HttpPost] public JsonResult AdminList(Models.AdminParamModel model) { int rowCount = 0; var result = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadPageList(model.RoleId, model.Mobile, model.iDisplayStart, model.iDisplayLength, model.IsDesc, out rowCount); return Json(new { sEcho = model.sEcho, iTotalRecords = rowCount, iTotalDisplayRecords = rowCount, aaData = result }, JsonRequestBehavior.AllowGet); } /// <summary> /// 获取管理员信息 /// </summary> /// <param name="id">管理员Id</param> /// <returns></returns> [HttpPost] public JsonResult GetAdminInfo(int id = 0) { var result = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadEntities(m => m.Id == id && m.IsSuperAdmin == 0).FirstOrDefault(); if (result == null) { return Json(new { state = "error", message = "无法找到该管理员信息" }); } else { return Json(new { state = "success", result }); } } /// <summary> /// 添加管理员 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public JsonResult AddAdmin(Models.AdminModel model) { if (ModelState.IsValid) { IDAL.IAdminRepository adminRepository = EnterRepository.GetRepositoryEnter().GetAdminRepository; //判断权限名称是否已存在 var result = adminRepository.LoadEntities(m => m.Mobile == model.Mobile.Trim()).FirstOrDefault(); if (result == null) { Random rn = new Random(); string salt = rn.Next(10000, 99999).ToString() + rn.Next(10000, 99999).ToString(); adminRepository.AddEntity(new Model.Admin() { AuthoryId = model.AuthoryId, CreateTime = DateTime.Now, IsLogin = model.IsLogin, Mobile = model.Mobile, IsSuperAdmin = 0, LastLoginTime = DateTime.Now, Salt = salt, Password = MD5Helper.CreatePasswordMd5("ad" + model.Mobile.Substring(7, 4), salt) }); //添加下操作记录 PublicFunction.AddOperation(1, string.Format("添加管理员"), string.Format("添加管理员=={0}==成功", model.Mobile)); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "添加管理员成功" }); } else { PublicFunction.AddOperation(1, string.Format("添加管理员"), string.Format("添加管理员=={0}==失败", model.Mobile)); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "添加管理员失败" }); } } else { return Json(new { state = "error", message = "手机号码已经存在了" }); } } else { return Json(new { state="error",message="信息不完整"}); } } /// <summary> /// 修改管理员 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public JsonResult UpdateAdmin(Models.AdminModel model) { if (ModelState.IsValid) { IDAL.IAdminRepository adminRepository = EnterRepository.GetRepositoryEnter().GetAdminRepository; //判断权限名称是否已存在 var result = adminRepository.LoadEntities(m => m.Mobile == model.Mobile.Trim()).FirstOrDefault(); if (result != null && result.Id != model.Id) { return Json(new { state = "error", message = "手机号码已经存在了" }); } else { Model.Admin admin = new Model.Admin() { AuthoryId = model.AuthoryId, IsLogin = model.IsLogin, Mobile = model.Mobile, Id = model.Id }; //清楚context中result对象 adminRepository.Get(m => m.Id == model.Id); adminRepository.EditEntity(admin, new string[] { "AuthoryId", "IsLogin", "Mobile" }); PublicFunction.AddOperation(1, string.Format("修改管理员"), string.Format("修改管理员=={0}==成功", model.Mobile)); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "修改管理员成功" }); } else { PublicFunction.AddOperation(1, string.Format("修改管理员"), string.Format("修改管理员=={0}==失败", model.Mobile)); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "修改管理员失败" }); } } } else { return Json(new { state = "error", message = "信息不完整" }); } } /// <summary> /// 更改管理员可登陆状态 /// </summary> /// <param name="id">管理员Id</param> /// <param name="state">管理员状态</param> /// <returns></returns> [HttpPost] public JsonResult UpdateState(int id = 0, int state = 0) { EnterRepository.GetRepositoryEnter().GetAdminRepository.EditEntity(new Model.Admin() { Id = id, IsLogin = (byte)state }, new string[] { "IsLogin" }); PublicFunction.AddOperation(1, string.Format("修改管理员可登陆状态"), string.Format("修改管理员可登陆状态成功")); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "修改管理员可登陆状态成功" }); } else { PublicFunction.AddOperation(1, string.Format("修改管理员可登陆状态"), string.Format("修改管理员可登陆状态失败")); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "服务器泡妞去了" }); } } /// <summary> /// 重置密码 /// </summary> /// <param name="id">管理员Id</param> /// <param name="newPassword">新密码</param> /// <returns></returns> [HttpPost] public JsonResult RestPassword(int id, string newPassword) { Random rn = new Random(); string salt = rn.Next(10000, 99999).ToString() + rn.Next(10000, 99999).ToString(); EnterRepository.GetRepositoryEnter().GetAdminRepository.EditEntity(new Model.Admin() { Id = id, Password = MD5Helper.CreatePasswordMd5(newPassword, salt), Salt = salt }, new string[] { "Password", "Salt" }); PublicFunction.AddOperation(1, string.Format("重置管理员密码"), string.Format("重置管理员=={0}==密码成功", id)); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "重置管理员密码成功" }); } else { PublicFunction.AddOperation(1, string.Format("重置管理员密码"), string.Format("修改管理员=={0}==可登陆状态失败", id)); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "服务器泡妞去了" }); } } /// <summary> /// 删除管理员 /// </summary> /// <param name="id">管理员Id</param> /// <returns></returns> [HttpPost] public JsonResult DeleteAdmin(int id = 0) { EnterRepository.GetRepositoryEnter().GetAdminRepository.DeleteEntity(new Model.Admin() { Id = id }); PublicFunction.AddOperation(1, string.Format("删除管理员"), string.Format("删除管理员成功")); if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) { return Json(new { state = "success", message = "删除管理员成功" }); } else { PublicFunction.AddOperation(1, string.Format("删除管理员"), string.Format("删除管理员失败")); EnterRepository.GetRepositoryEnter().SaveChange(); return Json(new { state = "error", message = "服务器泡妞去了" }); } } } }
页面代码
@section Header{ <style type="text/css"> /*加载动态图片*/ .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 100%; height: 40px; margin-left: -50%; margin-top: -25px; padding-top: 20px; text-align: center; font-size: 1.2em; /*background-color: white;*/ } </style> } <div class="main-content"> <div class="breadcrumbs" id="breadcrumbs"> <script type="text/javascript"> try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { } </script> <ul class="breadcrumb"> <li> <i class="icon-home home-icon"></i> <a href="/Admin/Home">首页</a> </li> <li> <a href="/Admin/Admin/AdminList">管理员列表</a> </li> <li class="active">管理员列表</li> </ul><!-- .breadcrumb --> <!-- #nav-search --> </div> <div class="page-content"> <div class="row"> <div class="col-xs-12"> <!-- PAGE CONTENT BEGINS --> <div class="row"> <div class="col-xs-12"> <div class="table-header"> 管理员列表查看 </div> <div class="hidden" id="hidden_filter"> @* 把需要搜索的条件放到hidden里面,在table格式化完成的时候直接调用$.html()赋值,免去了在js拼接标签的麻烦 *@ <div style="float:left;"> <label class="AddRole"> <a id="AddNewRole" class="btn btn-xs btn-primary" data-toggle="modal" href="" onclick="showAddNewAdmin()" title="添加新管理员"> <i class="icon-plus-sign bigger-130"></i> 添加新管理员 </a> </label> <label class="SearchRole"> <label>手机号码:</label> <label> @Html.TextBox("Mobile_Search", "", new { @class = "form-control input-small", style = "width:150px", placeholder = "请输入手机号码" }) </label> <label>选择角色: </label> <label> <select id="Authory_Search"> @foreach (var item in ViewBag.RoleSelectItem) { <option value="@item.Value">@item.Text</option> } </select> </label> <label> <a href="javascript:Search();" class="btn btn-xs btn-success"> <i class="icon-search bigger-130"></i> 搜索 </a> <i class="fa fa-search"></i> </label> </label> </div> </div> <div class="table-responsive dataTables_wrapper"> <table id="sample-table-2" class="table table-striped table-bordered table-hover"> <thead> <tr> <th class="center sorting_disabled" role="columnheader" rowspan="1" colspan="1" aria-label="" style="width: 58px;"> <label> <input type="checkbox" class="ace"> <span class="lbl"></span> </label> </th> <th>手机号码</th> <th>用户名</th> <th>邮箱</th> <th>角色名称</th> <th>上次登录时间</th> <th>是否可登陆</th> <th>创建时间</th> <th style="width: 120px;"> 操作 </th> </tr> </thead> </table> </div> </div> </div> <!-- PAGE CONTENT ENDS --> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.page-content --> </div> <div class="modal fade" id="ShowAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> @RenderPage("/Areas/Admin/Views/Admin/DisplayTemplates/AdminTemp.cshtml", new { SelectItem = ViewBag.RoleSelectItem }) </div> @section script{ <script src="/Content/assets/js/jquery.dataTables.min.js"></script> <script src="/Content/assets/js/jquery.dataTables.bootstrap.js"></script> <script src="/Content/assets/js/bootbox.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <script type="text/javascript"> var isSearch = false; $(function () { var objTable = $("#sample-table-2").dataTable({ aoColumns: [ { "sClass": "center", "mDataProp": "Id", "bSortable": false }, { "sClass": "center", "mDataProp": "Mobile", "bSortable": false }, { "sClass": "center", "mDataProp": "AdminName", "bSortable": false }, { "sClass": "center", "mDataProp": "Email", "bSortable": false }, { "sClass": "center", "mDataProp": "Name", "bSortable": false }, { "sClass": "center", "mDataProp": "LastLoginTime", "bSortable": false }, { "sClass": "center", "mDataProp": "IsLogin", "bSortable": false }, { "mDataProp": "CreateTime", "sClass": "center", "bSortable": true, "asSorting": ["asc", "desc"] }, { "sClass": "center", "mDataProp": "Id", "bSortable": false } ], "bServerSide": true,//分页,取数据等等的都放到服务端去 "bProcessing": true,//载入数据的时候是否显示“载入中” "aLengthMenu": [20, 30, 50, 100], "bLengthChange": true, //改变每页显示数据数量 //"bFilter": false, //过滤功能 "iDisplayStart": 0, "iDisplayLength": 20,//首次加载的数据条数 "bStorable": true,//排序操作在服务端进行,所以可以关了。 "sAjaxSource": "/Admin/Admin/AdminList", "fnServerParams": function (aoData, bStorable) { }, /*如果加上下面这段内容,则使用post方式传递数据*/ "fnServerData": function (sSource, aoData, fnCallback, bStorable) { var paramList = { "sEcho": 0, "iDisplayLength": 0, "iDisplayStart": 0, "isDesc": bStorable.aaSorting[0][1] == "desc" ? true : false, "RoleId": isSearch ==true?$("#Authory_Search").val() : -1, "Mobile": isSearch == true?$("#Mobile_Search").val() : "" }; if (bStorable.aaSorting[0][0] == 0) { paramList.isDesc = true; } for (var i = 0; i < aoData.length; i++) { if (aoData[i].name == "iDisplayStart") { paramList.iDisplayStart = aoData[i].value; } else if (aoData[i].name == "iDisplayLength") { paramList.iDisplayLength = aoData[i].value; } else if (aoData[i].name == "sEcho") { paramList.sEcho = aoData[i].value; } } $.ajax({ "dataType": 'json', "type": "POST", "url": sSource, "data": paramList, "success": function (resp) { fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式 } }); }, "oLanguage": { "sSearch": "搜索", "sLengthMenu": "每页显示 _MENU_ 条记录", "sZeroRecords": "抱歉, 没有找到", "sInfo": "从 _START_ 到 _END_ 共 _TOTAL_ 条数据", "sInfoEmpty": "没有数据", "sInfoFiltered": "(从 _MAX_ 条数据中检索)", "oPaginate": { "sFirst": "首页", "sPrevious": "前一页", "sNext": "后一页", "sLast": "尾页" }, "sZeroRecords": "没有检索到数据", "sProcessing": "<img src='/Content/assets/images/loading.gif' />" }, "fnRowCallback": function (nRow, aData, iDisplayIndex) { /* 用来改写指定行的样式 */ $('td:eq(0)', nRow).html("<label><input type=\"checkbox\" class=\"ace\" value=\"" + aData.Id + "\"><span class=\"lbl\"></span></label>"); $('td:eq(5)', nRow).html(GetDateYMR(aData.LastLoginTime)); $('td:eq(7)', nRow).html(GetDateYMR(aData.CreateTime)); var html = "<div class=\"visible-md visible-lg hidden-sm hidden-xs action-buttons\">"; // html += "<a class=\"blue\" href=\"#\"><i class=\"icon-zoom-in bigger-130\"></i></a>";//查看按钮 html += "<a class=\"green LookRole\" href=\"javascript:UpdateObj('" + aData.Id + "')\" title=\"编辑\"><i class=\"icon-pencil bigger-130\"></i></a>";//编辑 if (aData.IsLogin == 1) { $('td:eq(6)', nRow).html("<i class=\"icon-ok green bigger-120\"></i>"); html += "<a class=\"red UpdateRole\" href=\"javascript:CanLogin('" + aData.Id + "',0)\" title=\"不能登录\"><i class=\"icon-remove bigger-130\"></i></a>";//删除 } else { $('td:eq(6)', nRow).html("<i class=\"icon-remove red bigger-120\"></i>"); html += "<a class=\"green UpdateRole\" href=\"javascript:CanLogin('" + aData.Id + "',1)\" title=\"可登陆\"><i class=\"icon-ok bigger-130\"></i></a>"; } html += "<a class=\"red UpdateRole\" href=\"javascript:ShowPrompt('" + aData.Id + "')\" title=\"重置密码\"><i class=\"icon-refresh bigger-130\"></i></a>"; html += "<a class=\"red DeleteRole\" href=\"javascript:DeleteObj('" + aData.Id + "')\" title=\"删除管理员\"><i class=\"icon-trash bigger-130\"></i></a>";//删除 html += "</div>"; $('td:eq(8)', nRow).html(html); return nRow; } }); //下面的代码主要是将下拉框的位置已到右边去 $("#sample-table-2_length").parents().first().removeClass("col-sm-6").addClass("col-sm-3"); $("#sample-table-2_length").parents().first().css("float", "right"); $("#sample-table-2_filter").parents().first().removeClass("col-sm-6").addClass("col-sm-8"); $("#sample-table-2_filter").parents().first().css("float", "left"); $("#sample-table-2_length").css("float", "right"); $("#sample-table-2_filter").html($("#hidden_filter").html()); $("#hidden_filter").remove(); }) //搜索 function Search() { isSearch = true; $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 } function showAddNewAdmin() { $("#Id").val(0); $('#ShowAdd').modal(); } function UpdateObj(id) { $.ajax({ type: "post", data: { id: id }, url: "/Admin/Admin/GetAdminInfo", success: function (result) { if (result.state == "success") { $("#Id").val(id); $("#Mobile").val(result.result.Mobile); $("#AuthoryId option[value=" + result.result.AuthoryId + "]").attr("selected", "selected"); if (result.result.IsLogin == 1) { $("input[name='IsLogin']").eq(0).removeAttr("checked"); $("input[name='IsLogin']").eq(1).attr("checked", "checked"); } else { $("input[name='IsLogin']").eq(0).attr("checked", "checked"); $("input[name='IsLogin']").eq(1).removeAttr("checked"); } $('#ShowAdd').modal(); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) } $("#AddRoleForm").submit(function () { if ($("#AddRoleForm").valid()) { var url = "/Admin/Admin/AddAdmin"; if ($("#Id").val() > 0) { url = "/Admin/Admin/UpdateAdmin"; } $.ajax({ type: "post", data: $("#AddRoleForm").serialize(), url: url, success: function (result) { if (result.state == "success") { $('#ShowAdd').modal('hide');//关闭模态框 document.getElementById("AddRoleForm").reset();//清空表单 bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 }, message: result.message }); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) return false; } else { return false; } }) function CanLogin(id, state) { bootbox.confirm({ buttons: { confirm: { label: '确定', className: 'btn-primary' }, cancel: { label: '取消', className: 'btn-default' } }, message: state == 0 ? "确定禁止该管理员登录吗" : "确定恢复该管理员登录吗", callback: function (result) { if (result) { UpdateState(id, state) } } }); } function UpdateState(id, state) { $.ajax({ type: "post", data: { id: id, state: state }, url: "/Admin/Admin/UpdateState", success: function (result) { if (result.state == "success") { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 }, message: result.message }); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) } function DeleteObj(id) { bootbox.confirm({ buttons: { confirm: { label: '确定', className: 'btn-primary' }, cancel: { label: '取消', className: 'btn-default' } }, message: "确定要彻底删除该角色吗?", callback: function (result) { if (result) { $.ajax({ type: "post", data: { id: id }, url: "/Admin/Admin/DeleteAdmin", success: function (result) { if (result.state == "success") { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 }, message: result.message }); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) } } }); } function RestPassword(id,password) { $.ajax({ type: "post", data: { id: id, newPassword: password }, url: "/Admin/Admin/RestPassword", success: function (result) { if (result.state == "success") { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。 }, message: result.message }); } else { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { }, message: result.message }); } } }) } function ShowPrompt(id) { bootbox.prompt("请输入新的密码", function (result) { if (result == null) { } else if (result == "" || result.length < 6) { bootbox.alert({ buttons: { ok: { label: '我知道了', className: 'btn btn-primary' } }, callback: function () { ShowPrompt(id); }, message: '密码长度不能少于6位' }); } else { RestPassword(id, result) } }); } </script> } @model AuthorDesign.Web.Areas.Admin.Models.AdminModel <div class="main-content col-xs-8" style="margin-top: 70px; margin-left: 15%;"> <div class="page-content"> <div class="row"> <section> <div class="page-header"> <h1> 管理员管理 <small> <i class="icon-double-angle-right"></i> <span id="ShowText">管理员编辑</span> </small> </h1> </div> <div class="col-lg-10 col-lg-offset-2"> <form id="AddRoleForm" class="form-horizontal"> <fieldset> @Html.HiddenFor(m => m.Id) <div class="form-group"> <label class="col-lg-3 control-label">手机号码<span style="color:red;">*</span>:</label> <div class="col-lg-7" style="float:left;"> @Html.TextBoxFor(m => m.Mobile, new { @class = "col-sm-8" }) @Html.ValidationMessageFor(m => m.Mobile) </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">角色:</label> <div class="col-lg-7"> <select id="AuthoryId" name="AuthoryId"> @foreach (var item in ViewBag.RoleSelectItem) { <option value="@item.Value">@item.Text</option> } </select> @*@Html.DropDownListFor(m => m.AuthoryId, PageData["SelectItem"] as IEnumerable<SelectListItem>)*@ @Html.ValidationMessageFor(m => m.AuthoryId) </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">是否可登录</label> <div class="col-lg-7"> <label> <input name="IsLogin" type="radio" class="ace" value="0" checked="checked" /> <span class="lbl">不可登录</span> </label> <label> <input name="IsLogin" type="radio" class="ace" value="1" /> <span class="lbl">可登陆</span> </label> </div> </div> </fieldset> <div class="form-group"> <div class="col-lg-9 col-lg-offset-3"> <button class="btn btn-primary UpdateRole" type="submit"> <i class="icon-ok bigger-110"></i> 保存 </button> <button class="btn" type="reset" data-dismiss="modal"> <i class="icon-undo bigger-110"></i> 取消 </button> </div> </div> </form> </div> </section> <!-- /.row --> </div> </div> <!-- /.page-content --> </div>
页面效果
用户和页面按钮就这样完成了,最后,如果谁有稍微好弄一点的树形结构的样式,麻烦推荐我下,我打算在页面那边使用。