因为我目前运维的是一个webform项目,项目中未用到分页的功能,我百度了很多文章也没有一篇是结合jqgrid + ashx + nhibernate的分页,可能是因为后台要请求ashx的原因,不像mvc直接可以请求一个方法就可以了。

那就让我们从页面到后台来一步步解析jqgrid的分页吧。

1、初始化表格的代码如下

 function initGrid() {

        localGrid = jQuery("#tbList");
localGrid.jqGrid({
//data: localData,
url:"JqgridPageHandler.ashx",
datatype: "json",
gridview: true,
height: ,
width: '95%',
rowNum: ,
rowList: [, , , ],
colNames: columns,
autowidth: true,
hoverrows: false,
colModel: [
{ name: 'Id', hidden: true, index: 'Id', width: , key: true },
{ name: 'Name', index: 'Name', width: , align: "center" },
{ name: 'ExamType', index: 'ExamType', width: , align: "center" },
{ name: 'Score', index: 'Score', width: , align: "center" },
{ name: 'QuerySite', index: 'QuerySite', width: , align: "center" },
{ name: 'ExamTime', index: 'ExamTime', width: , formatter: "date", formatoptions: { srcformat: 'Y-m-d ', newformat: 'Y-m-d ' }, align: "center" },
{ name: 'CreatedTime', index: 'CreatedTime', width: , formatter: "date", formatoptions: { srcformat: 'Y-m-d ', newformat: 'Y-m-d ' }, align: "center" },
{ name: 'StatusText', index: 'StatusText', width: , align: "center" },
{ name: 'Remark', index: 'Remark', width: , align: "center" }
],
emptyrecords: "没有任何数据",
pager: "#pager",
viewrecords: true,
rownumbers: true,
//loadonce: true,
caption: "外语成绩单",
multiselect: false,
postData: {//参数
name: $j("#name").val(),
examType: $j("#examType").val(),
startDate: startDate,
endDate: endDate,
isCreateTime: document.getElementById("<%=rbcreatedtime.ClientID %>").checked
},
jsonReader: {
//rows: "rows",
//page: "page",
//total: "total", // 很重要 定义了 后台分页参数的名字。
//records: "records",
repeatitems: false, } }).navGrid('#pager', { edit: false, add: false, del: false, searchtext: "搜索" }, {}, {}, {}, { search: true, sopt: ['cn', 'eq', 'ge', 'gt', 'le', 'lt'] }); gridHelper.SetAutoResize(localGrid, -, -, true, true);
}

在这个初始化表格的代码中有几点是要注意的:

a. jsonReader中只要设置repeatitems 为 false就可以了 其它的被注掉的参数是默认的。

b. postData 参数是我们查询的条件。在调用这个方法时要初始化好参数对应的值。例如:startDate  和  endDate

2、在页面的JS执行入口加载数据可以这样写

jQuery(document).ready(function () {
initDate();
initGrid();
});
initDate()方法就是为了初始化参数的 startDate  和  endDate 的值

3、当我们进入页面时会调用2中的方法进入后台 JqgridPageHandler.ashx 中的ProcessRequest方法,我们再进入这个方法中看他是如何接收参数和构造返回值的吧.
 public void ProcessRequest(HttpContext context)
{
int pageSize = int.Parse(context.Request["rows"]);
int pageIndex = int.Parse(context.Request["page"]);
string name = context.Request["name"].ToString();
string examType = context.Request["examType"].ToString();
DateTime startDate =DateTime.Parse(context.Request["startDate"].ToString());
DateTime endDate = DateTime.Parse(context.Request["endDate"].ToString());
bool isCreateTime =bool.Parse(context.Request["isCreateTime"].ToString()); List<OilDigital.CGGL.BLL.Abroad.ES> eslist = ESService.GetByPage(isCreateTime, startDate, endDate, ProfileHelper.GetUnitCode(), name, examType, pageSize, pageIndex);
ISession session = NHibernateSessionManager.Instance.GetSession();
int count = ESService.GetCount(isCreateTime, startDate, endDate, ProfileHelper.GetUnitCode(), name, examType);
var resultJson = new { count = count, page = pageIndex, //总页数=(总页数+页大小-1)/页大小 total = (int)Math.Ceiling(((double) count) / pageSize),//总页数 rows = eslist };
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(resultJson)); }

context.Request["page"],context.Request["rows"]这个中的rows是jqgrid默认往后台传的参数,其它参数的都是我们在页面上通过postData构造的。
再看看我们返回的参数吧,前端页面要接收一个json的对象,其中rows中包括了行,total就总页数,count是总条数,page是当前页面。这样传到前台去就可以了。 另外我们页面上肯定还会加一个查询的按钮,点击查询时会重新去加载jqgrid.代码如下:
    function doQuery() {
initDate();
localGrid.jqGrid('clearGridData');
localGrid.jqGrid('setGridParam', {
url: 'JqgridPageHandler.ashx',
postData: {
name: $j("#name").val(),
examType: $j("#examType").val(),
startDate: startDate,
endDate: endDate,
isCreateTime: document.getElementById("<%=rbcreatedtime.ClientID %>").checked
},
datatype: "json",
mtype: 'post',
}).trigger('reloadGrid'); }

因为在用户点击查询时可能会修改查询代码,那postData这里带上修改后的查询代码是很重要的。


4、我们再来看看ESService.GetByPage 和 ESService.GetCount 方法是如何在NHibernate中实现的吧
  public List<ES> GetByPage(bool isCreateTime,DateTime startDate, DateTime endDate, string unitCode, string name, string examType, int pageSize, int pageNumber)
{
try
{
ISession session = NHibernateSessionManager.Instance.GetSession();
ICriteria criteria = session.CreateCriteria(typeof(ES));
if(isCreateTime)
{
criteria.Add(Expression.Between("CreatedTime", startDate, endDate));
}
else
{
criteria.Add(Expression.Between("ExamTime", startDate, endDate));
} if (!string.IsNullOrEmpty(unitCode))
criteria.Add(Expression.Like("CeaterUnitCode", unitCode.Trim() + "%"));
if (!string.IsNullOrEmpty(name))
{
criteria.Add(Expression.Eq("Name", name.Trim()));
}
if (!string.IsNullOrEmpty(examType))
{
criteria.Add(Expression.Like("ExamType", "%" + examType.Trim() + "%"));
}
criteria.AddOrder(Order.Desc("CreatedTime"));
criteria.SetFirstResult((pageNumber - ) * pageSize);
criteria.SetMaxResults(pageSize);
return ConvertToGenericList(criteria.List());
}
catch (Exception ex)
{ throw new Exception(ex.Message);
}
}

这里面可以看到分页方法 SetFirstResult  和 SetMaxResults   其它都是加的一些查询条件。

这个方法只是获取了分页的数据,现在还需要获取总的数据条数,请看如下的方法:

public int GetCount(bool isCreateTime,DateTime startDate, DateTime endDate, string unitCode, string name, string examType)
{
StringBuilder sb = new StringBuilder();
if(isCreateTime)
{
sb.AppendFormat("select count(*) from ES as es where es.CreatedTime between convert(datetime,'{0}',111) and convert(datetime,'{1}',111)", startDate, endDate);
}else
{
sb.AppendFormat("select count(*) from ES as es where es.ExamTime between convert(datetime,'{0}',111) and convert(datetime,'{1}',111)", startDate, endDate);
} if(!string.IsNullOrEmpty(unitCode))
{
sb.AppendFormat(" and es.CeaterUnitCode like '{0}%'", unitCode.Trim());
} if(!string.IsNullOrEmpty(name))
{
sb.AppendFormat(" and es.Name = '{0}'", name);
}
if(!string.IsNullOrEmpty(examType))
{
sb.AppendFormat(" and es.ExamType like '%{0}%'", examType);
}
IEnumerator enumerator = session.CreateQuery(sb.ToString()).List().GetEnumerator();
enumerator.MoveNext();
return (int)enumerator.Current;
}

查询数据总条数是我是通过sql写的,暂时我也没有发现是否可以通过Expression表达式写,就像上面的查询数据的方法一样。如果可以那会省一次事,不用还去搞sql.

到此从前端到后端所有的代码都讲解完了,后台项目的中都可以用这个分页的方法了。

有需要大量进行微信投票或点赞的朋友可以给我留言哦!

 
												

基于jqgrid + ashx + nhibernate的分页的更多相关文章

  1. 基于存储过程的MVC开源分页控件--LYB.NET.SPPager

    摘要 现在基于ASP.NET MVC的分页控件我想大家都不陌生了,百度一下一大箩筐.其中有不少精品,陕北吴旗娃杨涛大哥做的分页控件MVCPager(http://www.webdiyer.com/)算 ...

  2. 基于视觉的Web页面分页算法VIPS的实现源代码下载

    基于视觉的Web页面分页算法VIPS的实现源代码下载 - tingya的专栏 - 博客频道 - CSDN.NET 基于视觉的Web页面分页算法VIPS的实现源代码下载 分类: 技术杂烩 2006-04 ...

  3. 基于存储过程的MVC开源分页控件

    基于存储过程的MVC开源分页控件--LYB.NET.SPPager 摘要 现在基于ASP.NET MVC的分页控件我想大家都不陌生了,百度一下一大箩筐.其中有不少精品,陕北吴旗娃杨涛大哥做的分页控件M ...

  4. 利用JqGrid结合ashx及EF分页显示列表之二

    上一篇文章简单利用JqGrid及ashx进行一个数据列表的显示,要文的重点是利用EF的分页与JqGrid进行结合,EF本文只是简单运用所以没有很规范,重点还是JqGrid分页的实现;本实例把JqGri ...

  5. 基于Jquery+Ajax+Json+高效分页

    摘要 分页我相信大家存储过程分页已经很熟悉了,ajax更是耳熟能详了,更别说我们的json,等等. 如果说您没用过这些东东的话,我相信看完这篇博文会对您有帮助的,,如果有任何问题不懂或者有bug没问题 ...

  6. 基于Vue.js的表格分页组件

    有一段时间没更新文章了,主要是因为自己一直在忙着学习新的东西而忘记分享了,实在惭愧. 这不,大半夜发文更一篇文章,分享一个自己编写的一个Vue的小组件,名叫BootPage. 不了解Vue.js的童鞋 ...

  7. 基于Bootstrap仿淘宝分页控件实现

    .header { cursor: pointer } p { margin: 3px 6px } th { background: lightblue; width: 20% } table { t ...

  8. Ecside基于数据库的过滤、分页、排序

    首先ecside展现列表.排序.过滤(该三种操作以下简称为 RSF )的实现原理完全和原版EC一样, 如果您对原版EC的retrieveRowsCallback.sortRowsCallback.fi ...

  9. 基于Entity Framework的自定义分页,增删改的通用实现

    简介 之前写个一个基于Dapper的分页实现,现在再来写一个基于Entity Framework的分页实现,以及增删改的通用实现. 代码 还是先上代码:https://github.com/jinwe ...

随机推荐

  1. python文件处理-根据csv文件内容,将对应图像拷贝到指定文件夹

    内容涉及:文件遍历,读取csv指定列,拷贝文件,清理和创建文件 # -*- coding: utf-8 -*- import csv import os import sys import numpy ...

  2. 【Spring注解驱动开发】如何使用@Value注解为bean的属性赋值,我们一起吊打面试官!

    写在前面 在之前的文章中,我们探讨了如何向Spring的IOC容器中注册bean组件,讲解了有关bean组件的生命周期的知识.今天,我们就来一起聊聊@Value注解的用法. 项目工程源码已经提交到Gi ...

  3. Angular2-------Error: Unexpected value ‘undefined’ declared by the module ‘模块名

    请检查[app.module.ts]文件中的[declarations]模块最后是否多了一个逗号 (完)

  4. 【Oracle】如何模拟resmgr:cpu quantum

    看完该篇文章你可以了解如下问题:resmgr:cpu quantum等待事件的知识,如何模拟该等待事件,如何避免该事件. 数据库版本: SYS@zkm> select banner from v ...

  5. List AND Set

    第二章 List集合 Collection中的常用几个子类(java.util.List集合.java.util.Set集合). 1.1 List接口介绍 java.util.List接口继承自Col ...

  6. kubernetes-pod驱逐机制

    1.驱逐策略 kubelet持续监控主机的资源使用情况,并尽量防止计算资源被耗尽.一旦出现资源紧缺的迹象,kubelet就会主动终止部分pod的运行,以回收资源. 2.驱逐信号 以下是一些kubele ...

  7. 理解css中min-width和max-width,width与它们之间的区别联系

    css中,min-width是用来限制元素的最小宽度,max-width用来限制元素的最大宽度,也就是说当元素的width大于max-width,或者小于min-width.就被它们的值所代替,尤其适 ...

  8. 工作那么久,才知道的 SOLID 设计原则

    认识 SOLID 原则 无论是软件系统设计,还是代码实现,遵循有效和明确的设计原则,都利于系统软件灵活可靠,安全快速的落地,更重要的是能灵活地应对需求,简化系统扩展和维护,避免无效的加班.本文主要讨论 ...

  9. day51 作业

    用html搭建一个注册页面 <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...

  10. 龙芯开源社区上线.NET主页

    龙芯团队从2019年7 月份开始着手.NET Core的MIPS64支持研发,经过将近一年的研发,在2020年6月18日完成了里程碑性的工作,在github CoreCLR 仓库:https://gi ...