因为我目前运维的是一个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. activiti学习笔记一

    activiti学习笔记 在讲activiti之前我们必须先了解一下什么是工作流,什么是工作流引擎. 在我们的日常工作中,我们会碰到很多流程化的东西,什么是流程化呢,其实通俗来讲就是有一系列固定的步骤 ...

  2. Auto-keras API详解

    在网上找到的Auto-keras API详解,非常全面,防止丢失记录在这! Auto-Keras API详解(1)——安装Auto-Keras https://blog.csdn.net/weixin ...

  3. linux terminal---EOF

    we can use cat and eof to enter multiple lines content once.

  4. 飞越面试官(二)--JUC

    大家好!我是本号唯一官方指定没头屑的小便--怕屁林. JUC是什么东西?我相信很多经验尚浅的小伙伴部分都会为之一懵,我也是,三个字母都会读,连在一起就不知道在说什么,其实如果把它的全称写出来,“jav ...

  5. lodash - slice

    稀疏数组和密集数组 稀疏数组 Sparse arrays 一般来说,JavaScript 中的数组都是稀疏数组-它们可以拥有空槽,所谓空槽,指的就是数组的某个位置没有任何值,既不是 undefined ...

  6. 重学 Java 设计模式:实战状态模式「模拟系统营销活动,状态流程审核发布上线场景」

    作者:小傅哥 博客:https://bugstack.cn - 原创系列专题文章 沉淀.分享.成长,让自己和他人都能有所收获! @ 目录 一.前言 二.开发环境 三.状态模式介绍 四.案例场景模拟 1 ...

  7. Cache写策略(Cache一致性问题与骚操作)

    写命中 写直达(Write Through) 信息会被同时写到cache的块和主存中.这样做虽然比较慢,但缺少代价小,不需要把整个块都写回主存.也不会发生一致性问题. 对于写直达,多出来%10向主存写 ...

  8. ICPC 2018 亚洲横滨赛 C Emergency Evacuation(暴力,贪心)

    ICPC 2018 亚洲横滨赛 C Emergency Evacuation 题目大意 你一个车厢和一些人,这些人都坐在座位上,求这些人全部出去的时间最小值 Solution 题目咋说就咋做 直接模拟 ...

  9. 棋子游戏 51Nod - 1534 思维题

    题目描述 波雷卡普和瓦西里喜欢简单的逻辑游戏.今天他们玩了一个游戏,这个游戏在一个很大的棋盘上进行,他们每个人有一个棋子.他们轮流移动自己的棋子,波雷卡普先开始.每一步移动中,波雷卡普可以将他的棋子从 ...

  10. python学习笔记之数据类型(二)

    上一篇博客,小波介绍了python的入门和简单流程控制,这次写python的数据类型和各种数据类型的内置方法. 一.数据类型是何方神圣? 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当 ...