21. 重构js通用json数据处理方法、 top, 表示是顶层页面
1.重构js通用json数据处理方法
/*! ** Unobtrusive Ajax support library for jQuery ** Copyright (C) Microsoft Corporation. All rights reserved. */ /*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */ /*global window: false, jQuery: false */ (function ($) { $.extend($, { alertMsg: function (msg, title, funcSuc) { if ($.messager) { $.messager.alert(title, msg, function () { if (funcSuc) funcSuc(); }); } else { alert(title + "\r\n" + msg); if (funcSuc) funcSuc(); } }, //统一处理 返回的json数据格式 procAjaxData: function (data, funcSuc, funcErr) { if (!data||!data.Statu) { return; } switch (data.Statu) { case "ok": $.alertMsg(data.Msg, "系统提示", function () { funcSuc(data); }); // if (funcSuc) funcSuc(data); break; case "err": alertMsg(data.Msg, "系统提示", function () { funcErr(data); }); break; case "nologin": alertMsg(data.Msg, "系统提示", function () { window.location = data.BackUrl; }) break; } } }); //$.extend($, { // procAjaxData: function (data,funcSuc,funcErr) { // if (!data.Statu) { // return; // } // switch (data.Statu) // { // case "ok": // alert("OK:" + data.Msg); // if (funcSuc) funcSuc(data); // break; // case "err": // alert("ERR:" + data.Msg); // if (funcErr) funcErr(data); // break; // case "nologin": // alert(data.Msg); // window.location = data.BackUrl; // break; // } // } //}); }(jQuery));
========2.修改load没有权限,load返回的数据没有返回到function (jsonObj)回调函数里中去===================
2.修改load没有权限,load返回的数据没有返回到function (jsonObj)回调函数里中去。如:$("#editWindow").load("/admin/sys/EditPermission/" + rowData.pid, function (jsonObj);
3.现在我们自己加载用$.get加载修改。如:$.get("/admin/sys/EditPermission/" + rowData.pid, null, function (ResponseText)
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>用户权限管理</title> <link href="~/EasyUI/themes/icon.css" rel="stylesheet" /> <link href="~/EasyUI/themes/default/easyui.css" rel="stylesheet" /> <script type="text/javascript" src="~/Scripts/jquery.min.js"></script> <script type="text/javascript" src="~/EasyUI/jquery.easyui.min.js"></script> <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script> @*自动为表单 添加验证功能的js文件---微软提供 <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> *@ <script src="~/Scripts/jquery.msgProcess.js"></script> <script type="text/javascript"> //=====================1.加载数据====================== $(function () { $('#editWindow').window('close');//编辑默认关闭 $("#tbList").datagrid({ width: 'auto', height: 300, striped: true, singleSelect: true, url: '/admin/sys/GetPermData', //queryParams:{}, loadMsg: '数据加载中请稍后……', pagination: true, rownumbers: true, fitColumns:true, pageSize: 5, pageList:[5,10,15,20,25,30], columns: [[ { field: 'pid', title: 'ID', width: 100, align: "center" }, { field: 'pName', title: '权限名', width: 100, align: "center" }, { field: 'pAreaName', title: '区域名', width: 100, align: "center" }, { field: 'pControllerName', title: '控制名', width: 100, align: "center" }, { field: 'pActionName', title: 'Action', width: 100, align: "center" }, { field: 'pFormMethod', title: '请求方式', width: 100, align: "center", formatter: function (value) { //return value == "1" ? "Get" : "post"; switch (value.toString()) { case "1": return "Get"; case "2": return "Post"; case "3": return "Both"; } } }, { field: 'pOperationType', title: '操作类型', width: 100, align: "center", formatter: function (value) { switch (value.toString()) { case "0": return "无操作"; case "1": return "easyui连接"; case "2": return "打开新窗体"; break; } } } ]], toolbar: [{ iconCls: 'icon-add', text: "新增", handler: AddRow },'-', { iconCls: 'icon-remove', text: "删除", handler: Delperm }, '-', { iconCls: 'icon-edit', text: "编辑", handler: editRow }], //设置选中行 onSelect: function (rowI, rD) { selectRowIndex = rowI;//1.1将中的行设置为全局变量 设置给全局变量 } }); initMoifyForm(); }) ////为表单 设置 参数 function initMoifyForm() { $('#modifyForm').form({ url: "/admin/sys/EditPermission", }); } //1.将中的行设置为全局变量 var selectRowIndex = -1; //编辑按钮方法 function editRow() { //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected");//getSelected返回一个选中的行 if (rowData ==null) {//rowData如果没有选中,就什么不做 } if (rowData){ $('#editWindow').window('open');//打开 //load发送异步请求权限修改页面。并直接加载到 当前的 修改窗体中 //load加载修改数据没有返回到function(jsonObj)函数中去。所以需要要自己手写。 $("#editWindow").load("/admin/sys/EditPermission/" + rowData.pid, function (jsonObj) { alert("加载~~!" + jsonObj.statu);//返回加载~~!undefined });//路径、data、回调函数 } }; //新增按钮方法 function AddRow() { $('#editWindow').window('open');//打开 $("#editWindow").load("/admin/sys/AddPermission/");//路径、data、回调函数 } //删除方法 function Delperm() { //confirm("您确定要删除吗?"); //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected"); if (rowData) { //{id:rowData.pid} //$.post("/admin/sys/delpemission", rowData.pid, function () { }) $.post("/admin/sys/DelPermission", "id=" + rowData.pid, function () { $.procAjaxData(jsonOb); //成功了 $("#tbList").datagrid("reload");//删除成功后 刷新页面 }, "JSON"); } } </script> </head> <body> <table id="tbList" style="width:400px;height:250px"> </table> <div id="editWindow" class="easyui-window" title="用户权限编辑" style="width:600px;height:400px;" resizable="true" data-options="iconCls:'icon-save',modal:true"> </div> </body> </html>
运行效果:返回:加载~~!undefined
修改load没有权限,load返回的数据没有返回到function (jsonObj)回调函数里中去,加载不到,所以需要我们自己改下。
不用转json,因为返回的html代码就没法返回json。请求的是一个分布视图,是请求修改的的html代码,返回就判断下:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>用户权限管理</title> <link href="~/EasyUI/themes/icon.css" rel="stylesheet" /> <link href="~/EasyUI/themes/default/easyui.css" rel="stylesheet" /> <script type="text/javascript" src="~/Scripts/jquery.min.js"></script> <script type="text/javascript" src="~/EasyUI/jquery.easyui.min.js"></script> <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script> @*自动为表单 添加验证功能的js文件---微软提供 <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> *@ <script src="~/Scripts/jquery.msgProcess.js"></script> <script type="text/javascript"> //=====================1.加载数据====================== $(function () { $('#editWindow').window('close');//编辑默认关闭 $("#tbList").datagrid({ width: 'auto', height: 300, striped: true, singleSelect: true, url: '/admin/sys/GetPermData', //queryParams:{}, loadMsg: '数据加载中请稍后……', pagination: true, rownumbers: true, fitColumns:true, pageSize: 5, pageList:[5,10,15,20,25,30], columns: [[ { field: 'pid', title: 'ID', width: 100, align: "center" }, { field: 'pName', title: '权限名', width: 100, align: "center" }, { field: 'pAreaName', title: '区域名', width: 100, align: "center" }, { field: 'pControllerName', title: '控制名', width: 100, align: "center" }, { field: 'pActionName', title: 'Action', width: 100, align: "center" }, { field: 'pFormMethod', title: '请求方式', width: 100, align: "center", formatter: function (value) { //return value == "1" ? "Get" : "post"; switch (value.toString()) { case "1": return "Get"; case "2": return "Post"; case "3": return "Both"; } } }, { field: 'pOperationType', title: '操作类型', width: 100, align: "center", formatter: function (value) { switch (value.toString()) { case "0": return "无操作"; case "1": return "easyui连接"; case "2": return "打开新窗体"; break; } } } ]], toolbar: [{ iconCls: 'icon-add', text: "新增", handler: AddRow },'-', { iconCls: 'icon-remove', text: "删除", handler: Delperm }, '-', { iconCls: 'icon-edit', text: "编辑", handler: editRow }], //设置选中行 onSelect: function (rowI, rD) { selectRowIndex = rowI;//1.1将中的行设置为全局变量 设置给全局变量 } }); initMoifyForm(); }) ////为表单 设置 参数 function initMoifyForm() { $('#modifyForm').form({ url: "/admin/sys/EditPermission", }); } //1.将中的行设置为全局变量 var selectRowIndex = -1; //编辑按钮方法 function editRow() { //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected");//getSelected返回一个选中的行 if (rowData ==null) {//rowData如果没有选中,就什么不做 } if (rowData){ $('#editWindow').window('open');//打开 //load发送异步请求权限修改页面。并直接加载到 当前的 修改窗体中 //路径、data、回调函数 $.get("/admin/sys/EditPermission/" + rowData.pid, null, function (ResponseText) { //1.url,2.data,3.回调函数 alert(ResponseText);//返回修改的表单加载过来了 }); } }; //新增按钮方法 function AddRow() { $('#editWindow').window('open');//打开 $("#editWindow").load("/admin/sys/AddPermission/");//路径、data、回调函数 } //删除方法 function Delperm() { //confirm("您确定要删除吗?"); //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected"); if (rowData) { //{id:rowData.pid} //$.post("/admin/sys/delpemission", rowData.pid, function () { }) $.post("/admin/sys/DelPermission", "id=" + rowData.pid, function () { $.procAjaxData(jsonOb); //成功了 $("#tbList").datagrid("reload");//删除成功后 刷新页面 }, "JSON"); } } </script> </head> <body> <table id="tbList" style="width:400px;height:250px"> </table> <div id="editWindow" class="easyui-window" title="用户权限编辑" style="width:600px;height:400px;" resizable="true" data-options="iconCls:'icon-save',modal:true"> </div> </body> </html>
======== 3.现在我们自己加载用$.get加载修改========================================
//判断:传回来的数据是不是一个json格式数据,如果是统一执行方法返回
//编辑按钮方法 function editRow() { //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected");//getSelected返回一个选中的行 if (rowData ==null) {//rowData如果没有选中,就什么不做 } if (rowData){ $('#editWindow').window('open');//打开 //load发送异步请求权限修改页面。并直接加载到 当前的 修改窗体中 //路径、data、回调函数 $.get("/admin/sys/EditPermission/" + rowData.pid, null, function (ResponseText) { //1.url,2.data,3.回调函数 //判断:传回来的数据是不是一个json格式数据,如果是统一执行方法返回 //如果出错,则代表返回html代码 try { //授权没有权限,转换成json格式,转换成功说明没有权限 var jsonObj = JSON.parse(ResponseText);//调试过了,传过来的是html代码,所以转json格式会失败。 $.procAjaxData(jsonObj);//执行统一的执行方法 } catch (e) {//如果出错,则代表返回html代码 $('#editWindow').html(ResponseText);//失败了,就直接把html代码加到窗体上去。 } }); } };
====4.get=====
get请求修改页面返回fuction(responseText)已经帮我转转成字符串了;
1.所以就不需要try cath判断了。
2.if(jsonObj.Stau)
=====4.重构js通用json格式数据处理方法================
top, 表示是顶层页面, 因为页面之中可能嵌入了 frame 等子页面,top表示最外面一层
/*! ** Unobtrusive Ajax support library for jQuery ** Copyright (C) Microsoft Corporation. All rights reserved. */ /*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */ /*global window: false, jQuery: false */ (function ($) { $.extend($, { //显示消息:如果有easyui,则调用easyui的message组件显示消息 alertMsg: function (msg, title, funcSuc) { //error,question,info,warning if ($.messager) { $.messager.alert(title, msg, "info", function () { if (funcSuc) funcSuc(); }); } else { alert(title + "\r\n " + msg); if (funcSuc) funcSuc(); } }, //统一处理 返回的json数据格式 procAjaxData: function (data, funcSuc, funcErr) { if (!data || !data.Statu) { return; } switch (data.Statu) { case "ok": $.alertMsg(data.Msg, "系统提示", function () { funcSuc(data); }); break; case "err": $.alertMsg(data.Msg, "系统提示", function () { funcErr(data); }); break; case "nologin": $.alertMsg(data.Msg, "系统提示", function () { if (window.top) window.top.location = data.BackUrl; else window.location = data.BackUrl; }); break;//top, 表示是顶层页面, 因为页面之中可能嵌入了 frame 等子页面,top表示最外面一层 } } }); }(jQuery));
Permission.cshtml 用户权限管理
1.post删除成功后刷新,如果失败弹出消息:您现在删除的权限正在被角色使用,请先取消角色中的这个权限!
2.编辑:
//编辑按钮方法 function editRow() { //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected");//getSelected返回一个选中的行 if (rowData){ $('#editWindow').window('open');//2.打开 //load发送异步请求权限修改页面。并直接加载到 当前的 修改窗体中 //3.路径、data、回调函数 $.get("/admin/sys/EditPermission/" + rowData.pid, null, function (jsonObj) { //1.url,2.data,3.回调函数 if (jsonObj.Statu)//4.如果转了就是json对象,如果没转字符串就没有statu $.procAjaxData(jsonObj); else $('#editWindow').html(jsonObj); }); } };
3.新增
1如果新增存在json格式:也就是说jsonObj回调函数,jsonObj.Statu转成功,会弹出统一处理后的错误消息:没有权限或没有登陆。
2.把回调函数添加到html中。也就是新增窗体。
//新增按钮方法 function AddRow() { $('#editWindow').window('open');//打开 $.get("/admin/sys/AddPermission/", null, function (jsonObj) { if (jsonObj.Statu) $.procAjaxData(jsonObj); else { $("#editWindow").html(jsonObj); } });//路径、data、回调函数 }
Permission.cshtml 用户权限管理
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>用户权限管理</title> <link href="~/EasyUI/themes/icon.css" rel="stylesheet" /> <link href="~/EasyUI/themes/default/easyui.css" rel="stylesheet" /> <script type="text/javascript" src="~/Scripts/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="~/EasyUI/jquery.easyui.min.js"></script> <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script> @*自动为表单 添加验证功能的js文件---微软提供 <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> *@ <script type="text/javascript" src="~/Scripts/jquery.msgProcess.js"></script> <script type="text/javascript"> //=====================1.加载数据====================== $(function () { $('#editWindow').window('close');//编辑默认关闭 $("#tbList").datagrid({ width: 'auto', height: 400, striped: true, singleSelect: true, url: '/admin/sys/GetPermData', //queryParams:{}, loadMsg: '数据加载中请稍后……', pagination: true,//启用分页,默认每页10行 rownumbers: true,//显示页码,默认 提供 10 - 50 的页容量选择下拉框 pageSize: 10,//设置 页容量为 5 pageList: [10, 15, 20, 25, 30],//设置 页容量下拉框 fitColumns:true,//自动适应宽 columns: [[ { field: 'pid', title: 'ID', width: 100, align: "center" }, { field: 'pName', title: '权限名', width: 100, align: "center" }, { field: 'pAreaName', title: '区域名', width: 100, align: "center" }, { field: 'pControllerName', title: '控制名', width: 100, align: "center" }, { field: 'pActionName', title: 'Action', width: 100, align: "center" }, { field: 'pFormMethod', title: '请求方式', width: 100, align: "center", formatter: function (value) { switch (value.toString()) { case "1": return "Get"; case "2": return "Post"; case "3": return "Both"; } } }, { field: 'pOperationType', title: '操作类型', width: 100, align: "center", formatter: function (value) { switch (value.toString()) { case "0": return "无操作"; case "1": return "easyui连接"; case "2": return "打开新窗体"; break; } } } ]], toolbar: [{ iconCls: 'icon-add', text: "新增", handler: AddRow },'-', { iconCls: 'icon-remove', text: "删除", handler: Delperm }, '-', { iconCls: 'icon-edit', text: "编辑", handler: editRow }], //设置选中行 onSelect: function (rowI, rD) { selectRowIndex = rowI;//1.1将中的行设置为全局变量 设置给全局变量 } }); initMoifyForm(); }) ////为表单 设置 参数 function initMoifyForm() { $('#modifyForm').form({ url: "/admin/sys/EditPermission", }); } //1.将中的行设置为全局变量 var selectRowIndex = -1; //编辑按钮方法 function editRow() { //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected");//getSelected返回一个选中的行 //if (rowData ==null) {//rowData如果没有选中,就什么不做 //} if (rowData){ $('#editWindow').window('open');//打开 //load发送异步请求权限修改页面。并直接加载到 当前的 修改窗体中 //路径、data、回调函数 $.get("/admin/sys/EditPermission/" + rowData.pid, null, function (jsonObj) { //1.url,2.data,3.回调函数 if (jsonObj.Statu)//如果转了就是json对象,如果没转字符串就没有statu $.procAjaxData(jsonObj); else $('#editWindow').html(jsonObj); }); } }; //新增按钮方法 function AddRow() { $('#editWindow').window('open');//打开 $.get("/admin/sys/AddPermission/", null, function (jsonObj) { if (jsonObj.Statu) $.procAjaxData(jsonObj); else { $("#editWindow").html(jsonObj); } });//路径、data、回调函数 } //删除方法 function Delperm() { //confirm("您确定要删除吗?"); //1.获取选中行里的数据! var rowData = $("#tbList").datagrid("getSelected"); if (rowData) { //{id:rowData.pid} //$.post("/admin/sys/delpemission", rowData.pid, function () { }) $.post("/admin/sys/DelPermission", "id=" + rowData.pid, function (jsonObj) {//1.url,2.data,3.回调函数 $.procAjaxData(jsonObj, function () {//json统一处理方法:1.数据,2.删除成功后回调函数 $("#tbList").datagrid("reload");//删除成功后 刷新页面 }); //成功了 }, "JSON"); } } </script> </head> <body> <table id="tbList" style="width:400px;height:250px"> </table> <div id="editWindow" class="easyui-window" title="用户权限编辑" style="width:600px;height:400px;" resizable="true" data-options="iconCls:'icon-save',modal:true"> </div> </body> </html>
控制器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using MVCOA.Helper; using Common.Attributes; namespace MVCOA.Login.Admin { /// <summary> /// 系统管理 /// </summary> public class SysController : Controller { #region 1.0 权限列表 视图 +Permission() [HttpGet] /// <summary> /// 权限列表 视图 /// </summary> /// <returns></returns> public ActionResult Permission() { return View(); } #endregion #region 1.1 权限列表 数据 +GetPermData() [HttpPost] /// <summary> /// 权限列表 视图 /// </summary> /// <returns></returns> public ActionResult GetPermData() { SetDropDoneList(); //获取页容量 int pageSize = int.Parse(Request.Form["rows"]); //获取请求的页面 int pageIndex = int.Parse(Request.Form["page"]); //查询分页数据 var list = OperateContext.Current.BLLSession.IOu_PermissionBLL.GetPagedList(pageIndex, pageSize, p => p.pIsDel == false, p => p.pid).Select(p => p.ToPOCO()); //总行数 var rowCount = OperateContext.Current.BLLSession.IOu_PermissionBLL.GetListBy(p => p.pIsDel == false).Count(); MODEL.EasyUIModel.DataGridModel dgModel = new MODEL.EasyUIModel.DataGridModel() { total = rowCount, rows = list, footer = null }; return Json(dgModel); } #endregion #region 1.2加载 权限修改 窗体html [HttpGet] /// <summary> /// 1.2加载 权限修改 窗体html /// </summary> /// <returns></returns> public ActionResult EditPermission(int id)//这个是留有 { var listt = OperateContext.Current.BLLSession.IOu_PermissionBLL.GetListBy(c => c.pid == id).FirstOrDefault().ToViewModel(); //准备请求方式下拉框数据 SetDropDoneList(); return PartialView(listt); } #endregion #region 1.2 权限修改 +EditPermission(MODEL.ViewModel.Permission model) [HttpPost] [AjaxRequest] /// <summary> /// 1.2 权限修改 /// </summary> /// <returns></returns> public ActionResult EditPermission(MODEL.Ou_Permission model) { int res = OperateContext.Current.BLLSession.IOu_PermissionBLL.Modify(model, "pName", "pAreaName", "pControllerName", "pActionName", "pFormMethod", "pOperationType", "pOrder", "pIsShow", "pRemark"); if (res > 0) return Redirect("/admin/sys/Permission?ok"); else return Redirect("/admin/sys/Permission?err"); } #endregion #region 1.3显示 新增权限表单代码 [HttpGet] [AjaxRequest] /// <summary> /// 显示新增表单 /// </summary> /// <returns></returns> public ActionResult AddPermission() { //准备请求方式下拉框数据 SetDropDoneList(); return PartialView("EditPermission");//使用指定的视图创造呈现//partial局部的, } #endregion #region 1.3显示 新增权限表单代码 +EditPermission(MODEL.ViewModel.Permission model) [HttpPost] [AjaxRequest] /// <summary> /// 1.3显示 新增权限表单代码 /// </summary> /// <returns></returns> public ActionResult AddPermission(MODEL.Ou_Permission model) { model.pAddTime = DateTime.Now; model.pIsDel = false; int res = OperateContext.Current.BLLSession.IOu_PermissionBLL.Add(model); //下拉帮助类 SetDropDoneList(); if (res > 0) return Redirect("/admin/sys/Permission?ok"); else return Redirect("/admin/sys/Permission?err"); } #endregion #region 1.4删除权限操作+ActionResult DelPermission() /// <summary> /// 删除权限操作+DelPermission() /// </summary> /// <returns></returns> [HttpPost] [AjaxRequest] public ActionResult DelPermission() { try { int id = int.Parse(Request.Form["id"]);//获取要删除的id OperateContext.Current.BLLSession.IOu_PermissionBLL.DelBy(d => d.pid == id);//赋值给pid. return OperateContext.Current.RedirectAjax("ok", "删除成功了!!", null, ""); } catch { return OperateContext.Current.RedirectAjax("err", "您现在删除的权限正在被角色使用,请先取消角色中的这个权限!", null, ""); } } #endregion /// <summary> /// 下拉帮助类 /// </summary> void SetDropDoneList() { //准备请求方式下拉框数据 ViewBag.httpMethopList = new List<SelectListItem>() { new SelectListItem(){Text="Get",Value="1"}, new SelectListItem(){Text="Post",Value="2"}, new SelectListItem(){Text="Both",Value="3"}//Both两个都可以 }; //操作方式 ViewBag.OperationTypeList = new List<SelectListItem>() { new SelectListItem(){Text="无操作",Value="0"}, new SelectListItem(){Text="eastyui连接",Value="1"}, new SelectListItem(){Text="打开新窗体",Value="2"} }; } } }