最近很多小伙伴都在问和easyuidatagrid+mvc+json之asp.net分页查询这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展ASP.NETMVC5+EF6+Easy
最近很多小伙伴都在问和easyui datagrid+mvc+json之asp.net分页查询这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展ASP.NET MVC5+EF6+EasyUI 后台管理系统(92)-打印EasyUI 的datagrid表格、ASP.NET MVC中EasyUI的datagrid跨域调用实现代码_jquery、EasyUI Datagrid 分页事件、easyui datagrid 分页行乱码等相关知识,下面开始了哦!
本文目录一览:- (easyui datagrid+mvc+json)之asp.net分页查询(easyui分页传递表单参数)
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(92)-打印EasyUI 的datagrid表格
- ASP.NET MVC中EasyUI的datagrid跨域调用实现代码_jquery
- EasyUI Datagrid 分页事件
- easyui datagrid 分页行乱码
(easyui datagrid+mvc+json)之asp.net分页查询(easyui分页传递表单参数)
最近在做分页查询的功能,在网上也翻看了不少,但是自己的吸收能力就差了好多,而且当时最大的想法就是,怎么就没有我想要的那种,既是easyui的,又要用mvc的架构,还要能够实现底层的分页传值,用.net平台写的demo,那时就想,等我做出来了,我也要写一篇分页查询的博客,专门为了实现这种需求来做的demo。
效果图
前台view
<table id="list_data"cellpascing="0" cellpadding="0" ></table>
<script type="text/javascript"> //表格的样式 $(function(){ $('#list_data').datagrid({ title: '建议',iconCls: 'icon-view',//图标 loadMsg:"数据加载中,请稍后......",width:1056,height:'auto',Nowrap:false,striped:true,border:true,collapsible:false,//是否可折叠 fit:true,//自动大小 url: "/EvaluationSuggestion/GetData",//controller的地址,controller的名字+返回json的方法 remoteSort:false,singleSelect:true,//是否单选 pagination:true,//分页控件 rownumbers: false,//行号 columns: [[ { field: 'SuggestionContent',title: '建议',width: '1056' },//选择 ]],}); //设置分页控件 var p=$('#list_data').datagrid('getPager'); $(p).pagination({ pageNumber:1,//默认显示第几页 pageSize:10,Pagelist:[5,10,15],beforePageText:'第',afterPageText:'页 共{pages}页',displayMsg:'当前显示{from}-{to}条记录 共{total}条记录' }); }); </script>
解说:如果想要进行分页,首先就必须将datagrid的属性pagination设置为true。
pager是分页栏,这个标签用来设置分页的总体参数,
url是链接的重要根地址,pager标签会在这个链接的基础上附加分页参数。
Controller.cs
#region 查询建议的controller /// <summary> /// 查询建议的controller /// </summary> /// <returns>返回值action,用于与view层交互</returns> public ActionResult SuggestionIndex() { return View(); } #endregion #region 将建议数据转换成json字符串 /// <summary> /// 将建议数据转换成json字符串 /// </summary> /// <returns>返回json字符串</returns> public JsonResult GetData() { IEvaluationSuggestionWCF suggestion = ServiceFactory.GetEvaluationSuggestion(); List<EvaluationSuggestion> lstResut = new List<EvaluationSuggestion>(); //接收datagrid传来的参数 var pageIndex = int.Parse(Request["page"]); //当前页 var pageSize = int.Parse(Request["rows"]); //页面行数 var total = 0; lstResut = suggestion.QuerySuggestionbyPage(pageSize,pageIndex,out total); var data = new { total,rows = lstResut }; return Json(data,JsonRequestBehavior.AllowGet); } #endregion
解说:page和rows是直接可以从前台获取的。data设置数据格式,转换成Json字符串后,能够在分页中正确获取。
服务端
#region 分页查询 + 排序: /// <summary> /// 分页查询 + 排序 /// </summary> /// <typeparam name="Tkey">泛型</typeparam> /// <param name="pageSize">每页大小</param> /// <param name="pageIndex">当前页码</param> /// <param name="total">总数量</param> /// <param name="orderbyLambda">排序条件</param> /// <param name="isAsc">是否升序</param> /// <returns>IQueryable 泛型集合</returns> public IQueryable<T> LoadPageItems<Tkey>(int pageSize,int pageIndex,out int total,Func<T,Tkey> orderbyLambda,bool isAsc) { total = MyBaseDbContext.Set<T>().Count(); if (isAsc) { var temp = MyBaseDbContext.Set<T>().OrderBy<T,Tkey>(orderbyLambda) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize); return temp.AsQueryable(); } else { var temp = MyBaseDbContext.Set<T>().OrderByDescending<T,Tkey>(orderbyLambda) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize); return temp.AsQueryable(); } } #endregion
解说:这个是我们底层的类库,我直接贴过来的,底层使用EF,涉及到lambda表达式。不过除去形式,分页查询的思想都是一样的,真分页,根据记录总数,每页记录数和当前页码,获取当前页码的数据集合。页数=总记录数/每页记录数。当前页码的数据集合,向数据库传递条件筛选,from(当前页码-1)*每页记录数 to当前页码*每页记录数获取当前页码数据集合。具体实现自己来做吧。
ASP.NET MVC5+EF6+EasyUI 后台管理系统(92)-打印EasyUI 的datagrid表格
前言
应用系统有时候需要打印Datagrid的表格内容,我们本节就来学习打印datagrid内容
打印主要使用:web打印(我们之前有讲过web打印插件jqprint) + 将datagrid重新编制成可以打印的html格式
一、建立一个普通的例子
我们使用官方下载的demo下的datagrid basic.html代码就好
引入Jqgrid打印插件,并增加一个按钮来触发打印事件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic DataGrid - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
<link rel="stylesheet" type="text/css" href="../demo.css">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
<script src="jquery.jqprint-0.3.js"></script>
</head>
<body>
<h2>Basic DataGrid</h2>
<p>The DataGrid is created from markup, no JavaScript code needed.</p>
<div id="modalwindow"data-options="modal:true,closed:true,minimizable:false,shadow:false"></div>
<div><a href="#" id="btnPrint"data-options="iconCls:''icon-print''">Print</a></div>
<table id="List"title="Basic DataGrid"
data-options="singleSelect:true,collapsible:true,method:''get''">
<thead>
<tr>
<th data-options="field:''itemid'',width:80">Item ID</th>
<th data-options="field:''productid'',width:100">Product</th>
<th data-options="field:''listprice'',width:80,align:''right''">List Price</th>
<th data-options="field:''unitcost'',width:80,align:''right''">Unit Cost</th>
<th data-options="field:''attr1'',width:250">Attribute</th>
<th data-options="field:''status'',width:60,align:''center''">Status</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(function () {
//由于本地无法直接读取json文件,所以将数据提取出来赋值
var obj = {
"total": 28, "rows": [
{ "productid": "FI-SW-01", "productname": "Koi", "unitcost": 10.00, "status": "P", "listprice": 36.50, "attr1": "Large", "itemid": "EST-1" },
{ "productid": "K9-DL-01", "productname": "Dalmation", "unitcost": 12.00, "status": "P", "listprice": 18.50, "attr1": "Spotted Adult Female", "itemid": "EST-10" },
{ "productid": "RP-SN-01", "productname": "Rattlesnake", "unitcost": 12.00, "status": "P", "listprice": 38.50, "attr1": "Venomless", "itemid": "EST-11" },
{ "productid": "RP-SN-01", "productname": "Rattlesnake", "unitcost": 12.00, "status": "P", "listprice": 26.50, "attr1": "Rattleless", "itemid": "EST-12" },
{ "productid": "RP-LI-02", "productname": "Iguana", "unitcost": 12.00, "status": "P", "listprice": 35.50, "attr1": "Green Adult", "itemid": "EST-13" },
{ "productid": "FL-DSH-01", "productname": "Manx", "unitcost": 12.00, "status": "P", "listprice": 158.50, "attr1": "Tailless", "itemid": "EST-14" },
{ "productid": "FL-DSH-01", "productname": "Manx", "unitcost": 12.00, "status": "P", "listprice": 83.50, "attr1": "With tail", "itemid": "EST-15" },
{ "productid": "FL-DLH-02", "productname": "Persian", "unitcost": 12.00, "status": "P", "listprice": 23.50, "attr1": "Adult Female", "itemid": "EST-16" },
{ "productid": "FL-DLH-02", "productname": "Persian", "unitcost": 12.00, "status": "P", "listprice": 89.50, "attr1": "Adult Male", "itemid": "EST-17" },
{ "productid": "AV-CB-01", "productname": "Amazon Parrot", "unitcost": 92.00, "status": "P", "listprice": 63.50, "attr1": "Adult Male", "itemid": "EST-18" }
]
}
;
//加载数据
$(''#List'').datagrid(''loadData'', obj);
});
</script>
</body>
</html>
二、将datagrid数据分解成HTML Table表格
function CreateFormPage(printDatagrid) {
var tableString = ''<div><a onclick="$(\''.dg-pb\'').jqprint();"><span></span> 打印</a></div><table cellspacing="0">'';
var frozenColumns = printDatagrid.datagrid("options").frozenColumns; // 得到frozenColumns对象
var columns = printDatagrid.datagrid("options").columns; // 得到columns对象
var nameList = '''';
// 载入title
if (typeof columns != ''undefined'' && columns != '''') {
$(columns).each(function (index) {
tableString += ''\n<tr>'';
if (typeof frozenColumns != ''undefined'' && typeof frozenColumns[index] != ''undefined'') {
for (var i = 0; i < frozenColumns[index].length; ++i) {
if (!frozenColumns[index][i].hidden) {
tableString += ''\n<th width="'' + frozenColumns[index][i].width + ''"'';
if (typeof frozenColumns[index][i].rowspan != ''undefined'' && frozenColumns[index][i].rowspan > 1) {
tableString += '' rowspan="'' + frozenColumns[index][i].rowspan + ''"'';
}
if (typeof frozenColumns[index][i].colspan != ''undefined'' && frozenColumns[index][i].colspan > 1) {
tableString += '' colspan="'' + frozenColumns[index][i].colspan + ''"'';
}
if (typeof frozenColumns[index][i].field != ''undefined'' && frozenColumns[index][i].field != '''') {
nameList += '',{"f":"'' + frozenColumns[index][i].field + ''", "a":"'' + frozenColumns[index][i].align + ''"}'';
}
tableString += ''>'' + frozenColumns[0][i].title + ''</th>'';
}
}
}
for (var i = 0; i < columns[index].length; ++i) {
if (!columns[index][i].hidden) {
tableString += ''\n<th width="'' + columns[index][i].width + ''"'';
if (typeof columns[index][i].rowspan != ''undefined'' && columns[index][i].rowspan > 1) {
tableString += '' rowspan="'' + columns[index][i].rowspan + ''"'';
}
if (typeof columns[index][i].colspan != ''undefined'' && columns[index][i].colspan > 1) {
tableString += '' colspan="'' + columns[index][i].colspan + ''"'';
}
if (typeof columns[index][i].field != ''undefined'' && columns[index][i].field != '''') {
nameList += '',{"f":"'' + columns[index][i].field + ''", "a":"'' + columns[index][i].align + ''"}'';
}
tableString += ''>'' + columns[index][i].title + ''</th>'';
}
}
tableString += ''\n</tr>'';
});
}
// 载入内容
var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行
var nl = eval(''(['' + nameList.substring(1) + ''])'');
for (var i = 0; i < rows.length; ++i) {
tableString += ''\n<tr>'';
$(nl).each(function (j) {
var e = nl[j].f.lastIndexOf(''_0'');
tableString += ''\n<td'';
if (nl[j].a != ''undefined'' && nl[j].a != '''') {
tableString += '''';
}
tableString += ''>'';
if (e + 2 == nl[j].f.length) {
if (rows[i][nl[j].f.substring(0, e)] != null) {
tableString += rows[i][nl[j].f.substring(0, e)];
} else {
tableString += "";
}
}
else {
if (rows[i][nl[j].f] != null) {
tableString += rows[i][nl[j].f];
} else {
tableString += "";
}
}
tableString += ''</td>'';
});
tableString += ''\n</tr>'';
}
tableString += ''\n</table>'';
return tableString;
}
代码看起来有点复杂,但是不难看懂,提取datagrid的title和历遍数据得重新写入一个新的table
三、添加打印事件
$("#btnPrint").click(function () {
var tablestr = CreateFormPage($("#List"));
$("#modalwindow").html(tablestr);
$("#modalwindow").window({ title: "打印", width:500, height: 400, iconCls: ''fa fa-plus'' }).window(''open'');
});
四、预览结果
总结:
不是很美观,那么加入一段CSS吧
/*datagrid print*/
.dg-pb{font-size:13px;border-collapse:collapse;}
.dg-pb th{font-weight:bold;text-align:center;border:1px solid #333333;padding:2px;}
.dg-pb td{border:1px solid #333333;padding:2px;}
再次在预览的结果点击打印调出打印机
本节完整代码下载


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic DataGrid - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
<link rel="stylesheet" type="text/css" href="../demo.css">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
<script src="jquery.jqprint-0.3.js"></script>
</head>
<body>
<style>
/*datagrid print*/
.dg-pb{font-size:13px;border-collapse:collapse;}
.dg-pb th{font-weight:bold;text-align:center;border:1px solid #333333;padding:2px;}
.dg-pb td{border:1px solid #333333;padding:2px;}
</style>
<h2>Basic DataGrid</h2>
<p>The DataGrid is created from markup, no JavaScript code needed.</p>
<div id="modalwindow"data-options="modal:true,closed:true,minimizable:false,shadow:false"></div>
<div><a href="#" id="btnPrint"data-options="iconCls:''icon-print''">Print</a></div>
<table id="List"title="Basic DataGrid"data-options="singleSelect:true,collapsible:true,method:''get''">
<thead>
<tr>
<th data-options="field:''itemid'',width:80">Item ID</th>
<th data-options="field:''productid'',width:100">Product</th>
<th data-options="field:''listprice'',width:80,align:''right''">List Price</th>
<th data-options="field:''unitcost'',width:80,align:''right''">Unit Cost</th>
<th data-options="field:''attr1'',width:250">Attribute</th>
<th data-options="field:''status'',width:60,align:''center''">Status</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(function () {
var obj = {
"total": 28, "rows": [
{ "productid": "FI-SW-01", "productname": "Koi", "unitcost": 10.00, "status": "P", "listprice": 36.50, "attr1": "Large", "itemid": "EST-1" },
{ "productid": "K9-DL-01", "productname": "Dalmation", "unitcost": 12.00, "status": "P", "listprice": 18.50, "attr1": "Spotted Adult Female", "itemid": "EST-10" },
{ "productid": "RP-SN-01", "productname": "Rattlesnake", "unitcost": 12.00, "status": "P", "listprice": 38.50, "attr1": "Venomless", "itemid": "EST-11" },
{ "productid": "RP-SN-01", "productname": "Rattlesnake", "unitcost": 12.00, "status": "P", "listprice": 26.50, "attr1": "Rattleless", "itemid": "EST-12" },
{ "productid": "RP-LI-02", "productname": "Iguana", "unitcost": 12.00, "status": "P", "listprice": 35.50, "attr1": "Green Adult", "itemid": "EST-13" },
{ "productid": "FL-DSH-01", "productname": "Manx", "unitcost": 12.00, "status": "P", "listprice": 158.50, "attr1": "Tailless", "itemid": "EST-14" },
{ "productid": "FL-DSH-01", "productname": "Manx", "unitcost": 12.00, "status": "P", "listprice": 83.50, "attr1": "With tail", "itemid": "EST-15" },
{ "productid": "FL-DLH-02", "productname": "Persian", "unitcost": 12.00, "status": "P", "listprice": 23.50, "attr1": "Adult Female", "itemid": "EST-16" },
{ "productid": "FL-DLH-02", "productname": "Persian", "unitcost": 12.00, "status": "P", "listprice": 89.50, "attr1": "Adult Male", "itemid": "EST-17" },
{ "productid": "AV-CB-01", "productname": "Amazon Parrot", "unitcost": 92.00, "status": "P", "listprice": 63.50, "attr1": "Adult Male", "itemid": "EST-18" }
]
}
;
$(''#List'').datagrid(''loadData'', obj);
$("#btnPrint").click(function () {
var tablestr = CreateFormPage($("#List"));
$("#modalwindow").html(tablestr);
$("#modalwindow").window({ title: "打印", width:700, height: 400, iconCls: ''fa fa-plus'' }).window(''open'');
});
});
function CreateFormPage(printDatagrid) {
var tableString = ''<div> <a href="#" id="btnPrint"data-options="iconCls:\''icon-print\''"onclick="$(\''.dg-pb\'').jqprint();">打印</a></div><table cellspacing="0">'';
var frozenColumns = printDatagrid.datagrid("options").frozenColumns; // 得到frozenColumns对象
var columns = printDatagrid.datagrid("options").columns; // 得到columns对象
var nameList = '''';
// 载入title
if (typeof columns != ''undefined'' && columns != '''') {
$(columns).each(function (index) {
tableString += ''\n<tr>'';
if (typeof frozenColumns != ''undefined'' && typeof frozenColumns[index] != ''undefined'') {
for (var i = 0; i < frozenColumns[index].length; ++i) {
if (!frozenColumns[index][i].hidden) {
tableString += ''\n<th width="'' + frozenColumns[index][i].width + ''"'';
if (typeof frozenColumns[index][i].rowspan != ''undefined'' && frozenColumns[index][i].rowspan > 1) {
tableString += '' rowspan="'' + frozenColumns[index][i].rowspan + ''"'';
}
if (typeof frozenColumns[index][i].colspan != ''undefined'' && frozenColumns[index][i].colspan > 1) {
tableString += '' colspan="'' + frozenColumns[index][i].colspan + ''"'';
}
if (typeof frozenColumns[index][i].field != ''undefined'' && frozenColumns[index][i].field != '''') {
nameList += '',{"f":"'' + frozenColumns[index][i].field + ''", "a":"'' + frozenColumns[index][i].align + ''"}'';
}
tableString += ''>'' + frozenColumns[0][i].title + ''</th>'';
}
}
}
for (var i = 0; i < columns[index].length; ++i) {
if (!columns[index][i].hidden) {
tableString += ''\n<th width="'' + columns[index][i].width + ''"'';
if (typeof columns[index][i].rowspan != ''undefined'' && columns[index][i].rowspan > 1) {
tableString += '' rowspan="'' + columns[index][i].rowspan + ''"'';
}
if (typeof columns[index][i].colspan != ''undefined'' && columns[index][i].colspan > 1) {
tableString += '' colspan="'' + columns[index][i].colspan + ''"'';
}
if (typeof columns[index][i].field != ''undefined'' && columns[index][i].field != '''') {
nameList += '',{"f":"'' + columns[index][i].field + ''", "a":"'' + columns[index][i].align + ''"}'';
}
tableString += ''>'' + columns[index][i].title + ''</th>'';
}
}
tableString += ''\n</tr>'';
});
}
// 载入内容
var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行
var nl = eval(''(['' + nameList.substring(1) + ''])'');
for (var i = 0; i < rows.length; ++i) {
tableString += ''\n<tr>'';
$(nl).each(function (j) {
var e = nl[j].f.lastIndexOf(''_0'');
tableString += ''\n<td'';
if (nl[j].a != ''undefined'' && nl[j].a != '''') {
tableString += ''color: #0000ff;">'' + nl[j].a + '';"'';
}
tableString += ''>'';
if (e + 2 == nl[j].f.length) {
if (rows[i][nl[j].f.substring(0, e)] != null) {
tableString += rows[i][nl[j].f.substring(0, e)];
} else {
tableString += "";
}
}
else {
if (rows[i][nl[j].f] != null) {
tableString += rows[i][nl[j].f];
} else {
tableString += "";
}
}
tableString += ''</td>'';
});
tableString += ''\n</tr>'';
}
tableString += ''\n</table>'';
return tableString;
}
</script>
</body>
</html>
ASP.NET MVC中EasyUI的datagrid跨域调用实现代码_jquery
最近项目中需要跨域调用其他项目的数据,其他项目也是使用的EasyUI的datagrid组件,开始以为直接在datagrid的url属性定义为其他项目的url地址即可,可是测试下发现的确是返回了json数据但是json数据提示“invalid label” 错误,网上搜索了下错误解决办法,参考 “JavaScript处理Json的invalid label错误解决办法“的方法利用datagrid的loadData方法加载并转换了json还是提示上述错误,感觉原因不在格式问题。
搜索了下JavaScript跨域调用的文章“JavaScript跨域访问问题解决方法”得到启发,发现原来是因为easyUI使用的是JQuery的异步方法加载数据,应该遵循JQuery的跨域访问规则,也就是上述文章中提到的url中需要加入jsoncallback=?回调函数参数,并且返回的json的格式必须修改为:回调函数名(json数据),而现在返回的数据只是json格式的数据没有回调函数名,自然提示格式错误,于是修改了ASP.NET MVC自定义的JsonResult类,具体如何编写自定义的JsonResult类见:自定义ASP.NET MVC JsonResult序列化结果,
代码如下:
public class CustomJsonResult:JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
#pragma warning disable 0618
//跨域调用需要修改json格式jsoncallback
if (context.HttpContext.Request.Params.AllKeys.Contains("jsoncallback"))
{
String callback = context.HttpContext.Request.Params["jsoncallback"];
response.Write(callback+"("+JsonConvert.SerializeObject(Data)+")");
}
else
{
response.Write(JsonConvert.SerializeObject(Data));
}
#pragma warning restore 0618
}
}
}
EasyUI的datagrid的代码如下:
//datagrid
$(''#dg'').datagrid({
url:''http://localhost:9000/ManagementSystem/ListCurrent?department=sss&jsoncallback=?'',
pageNumber: 1,
pageSize: 20,
pageList: [20, 40, 60, 80, 100],
onDblClickRow: function(rowIndex) {
edit();
}
});