Asp.Net+Jquery Ajax异步分页

前段时间做的一个项目,需要实现的功能是弹出一个选择数据的窗口,里面的数据是可以分页的,选择相应的行数据填充到页面的文本框中(将其中的分页数据做成了Ajax 异步取数据),下面的分页导航按钮是仿照 博客园 做的,给自己做一个记录。

效果如下:第5页数据

做法是先做一个 分页取数据的 JS 类(好像JS没有类的概念...)(代码中有注释)

JS分页类
function AjaxPager(args) {
var defaults = { //一部分默认值
current: 1,
pageSize: 10
};
var args = $.extend(defaults, args); //将传进来的参数和默认值进行合并
this.current = args.current; //当前页索引
this.pageSize = args.pageSize; //分页大小
this.url = args.url; //要执行异步获取数据的处理程序url
this.handler = args.handler; //事件处理函数
}
AjaxPager.prototype = {
loadPrevPage: function() { //加载上一页数据的方法
this.loadPage(this.current - 1); //即当前页索引-1
},
loadPage: function(n) { //加载某一页的数据的方法
var _this = this;
_this.current = n;
var queryData = { //构造传递给处理页面的数据 相当于$.get(url,data,function) 中的data
pageSize: this.pageSize,
//cols: this.cols,
orderField: this.orderField,
//dir: this.dir,
pageIndex: n
//table: this.table
};
$.ajax({ //调用Jquery的 ajax方法
type: "post",
dataType: "json", //指定返回的数据类型为JSON格式
url: _this.url,
data: queryData,
success: function(data) { _this.handler(data, _this) }
});
},
loadNexPage: function() { //加载下一页数据的方法
this.loadPage(this.current + 1);
}
};

在城市类中写好取得分页数据的方法:

城市类
public class CityInfo
{
public CityInfo()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public int ID { get; set; }
public string CityID{get; set;}
public string City{get;set;}
public string Father { get; set; }

/// <summary>
/// 取城市的分页数据
/// </summary>
/// <param name="pageindex">页索引</param>
/// <param name="pagesize">页大小</param>
/// <param name="orderfield">排序字段</param>
/// <param name="ordertype">排序方式(asc或desc)</param>
/// <param name="condition">查询条件 如果没有条件时需传入:1=1</param>
/// <param name="recordCount">查询到的总的记录数</param>
/// <returns></returns>
public static IList<CityInfo> GetListByPage(int pageindex,int pagesize,string orderfield,string ordertype,string condition,ref int recordCount)
{
IList<CityInfo> Citys = new List<CityInfo>();
string Sql = string.Empty;
if (pageindex == 1)
{
Sql = "select top " + pagesize + " * from city where " + condition + " order by " + orderfield + " " + ordertype;
}
else {
//因为我的数据库是用access做的测试,考虑到Access的查询效率,用的是如下构建查询的方式(大于最大ID,小于最小ID方式)
if (ordertype == "asc") //如果是升序
{
//Sql = "select top " + pagesize + " * from area where " + orderfield + ">(select max(" + orderfield + ") from (select top " + (pageindex - 1) * pagesize + " " + orderfield + " from area where 1=1 order by " + orderfield + " asc)) order by " + orderfield + " asc";
Sql = "select top " + pagesize + " * from city where " + orderfield + ">(select max(" + orderfield + ") from (select top " + (pageindex - 1) * pagesize + " " + orderfield + " from city where "+condition+" order by " + orderfield + " asc)) and "+condition+" order by " + orderfield + " asc";
}
else//否则降序
{
//Sql = "select top " + pagesize + " * from area where " + orderfield + "<(select min(" + orderfield + ") from (select top " + (pageindex - 1) * pagesize + " " + orderfield + " from area where 1=1 order by " + orderfield + " desc)) order by " + orderfield + " desc";
Sql = "select top " + pagesize + " * from city where " + orderfield + "<(select min(" + orderfield + ") from (select top " + (pageindex - 1) * pagesize + " " + orderfield + " from city where " + condition + " order by " + orderfield + " desc)) and " + condition + " order by " + orderfield + " desc";
}
}
using (OleDbDataReader reader = OleDBHelper.ExecuteReader(Sql)) {
while (reader.Read()) {
CityInfo city = new CityInfo();
city.ID = Convert.ToInt32(reader["id"].ToString());
city.CityID = reader["cityID"].ToString();
city.City = reader["city"].ToString();
city.Father = reader["father"].ToString();
Citys.Add(city);
}
}
recordCount = GetRecordsCount(condition);
return Citys;
}

public static int GetRecordsCount(string condition) //根据查询条件取得总的数据记录数
{
string sql = "select count(1) from city where " + condition;
return (int)OleDBHelper.GetSingle(sql);
}
}

接着是用于取数据的一般处理程序 handler.ashx(数据的返回格式是JSON,用到了转换工具 Newtonsoft)

使用时只要引入命名空间 using Newtonsoft.Json就可以使用

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
System.Web.HttpResponse Response = context.Response;
System.Web.HttpRequest Request = context.Request;
//string sql = "select * from wr_menu_b order by id asc";
//string cols = Request["cols"].ToString();
//string table = Request["table"].ToString();
//string orderField = Request["orderField"].ToString();
//string dir = Request["dir"].ToString();
int pageSize = Convert.ToInt32(Request["pageSize"]!=null?Request["pageSize"].ToString():"10");
int pageIndex = Convert.ToInt32(Request["pageIndex"]!=null?Request["pageIndex"].ToString():"1");
string start = ((pageIndex - 1) * pageSize).ToString(); //从哪条记录开始
//string sql = "select " + cols + " from " + table + " order by " + orderField + " " + dir+" limit "+start+","+pageSize;

//Response.Write(sql);
//pageSize = 10;
//pageIndex = 4;
int recordCount = 0;
IList<CityInfo> citys = CityInfo.GetListByPage(pageIndex, pageSize, "id","asc","1=1", ref recordCount);
string result = JsonConvert.SerializeObject(citys);
int totalpage = 0;
if (recordCount % pageSize == 0)
totalpage = recordCount / pageSize;
else
totalpage = recordCount / pageSize + 1;


Response.Write("{\"total\": \"" + totalpage.ToString() + "\",\"curPage\":\"" + pageIndex + "\", \"records\": \"" + recordCount.ToString() + "\", \"rows\" : " + result + "}");
}

public bool IsReusable {
get {
return false;
}
}
}

 

整个城市页面的代码如下:

HTML页面代码(含样式)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>异步分页测试</title>
<script src="../js/jquery-1.4.min.js" type="text/javascript"></script>
<script src="AjaxPager.js" type="text/javascript"></script>
<style type="text/css">
/*全局样式*/
*{margin:0; padding:0;}
body{font-size:12px; font-family:Arial,宋体,Times New Roman; overflow: hidden; text-align:center;}
ul{list-style-type:none;}
:focus{outline:0;}
.clear{ clear:both; font-size:0; line-height:0;}
a.img{border:none;}

h1{font-size:14px;}
#Citys{width:500px; border-right:1px solid #f60; border-top:1px solid #f60;}
#Citys td, #Citys th{padding:3px; height:18px; border-left:1px solid #f60; border-bottom:1px solid #f60;}
#Citys tr th{color:Red; background:#CCC;}
#Citys tr.thead th{height:22px;color:#FFF; background:#F60;}
#Citys tr.odd{background:#ccc;}
#Citys tr.hover{background:#ccc;}




.pageBtns{font-size:12px; color:#29597D; padding-top:8px; text-align:center;}
.pageBtns a{border:1px solid #9AAFE5; padding:2px 5px; background-color:#FFF; margin-right:5px; color:#776AC1; text-decoration:none;}
.pageBtns a.current{border-color:#000080; background-color:#2E6AB1; font-weight:bold; color:#FFF;}
.pageBtns a.disable{color:#B8D5E9; cursor:default; background-color:#ECF3FE;}
</style>
<script type="text/javascript">
$(document).ready(function() {
var PageCity = new AjaxPager({
current: 1,
pageSize: 10,
url: "Handler.ashx?temp=" + (+new Date),
handler: formatData //事件处理函数
});
PageCity.loadPage(1); //页面加载完成后就加载第一页
});
function selectName(name, id) {
alert(name + "\n" + id);
};
function formatData(data, page) { //分别代表查找到的数据和当前的AjaxPager对象

//TODO:应要做一下如果没有数据的判断

var tb = $("#Citys"); //构建数据的显示
var strHtml = '<tr class="thead"><th colspan="4">中国主要城市一览</th></tr><tr><th style="width:80px">编号</th><th>城市编号</th><th>城市名称</th><th>所属区域编号</th></tr>';
var str = data;
$("#totalCount").html(str.records);
$("#totalPage").html(str.total);
$("#curPage").val(str.curPage);
for (var i = 0; i < str.rows.length; i++) {
//strHtml += "<tr onclick='selectName(&quot;" + str.rows[i].Id + "&quot;,&quot;" + str.rows[i].Name + "&quot;)'><td>" + str.rows[i].Id + "</td><td>" + str.rows[i].Name + "</td><td>修改&删除还没有做</td>";
strHtml += '<tr onclick="selectName(&quot;'+str.rows[i].City+'&quot;,&quot;'+str.rows[i].ID+'&quot;)"><td>'+str.rows[i].ID+'</td><td>'+str.rows[i].CityID+'</td><td>'+str.rows[i].City+'</td><td>'+str.rows[i].Father+'</td></tr>';
}
//alert(strHtml);
tb.html(strHtml);
tb.find("tr:gt(1):odd").addClass("odd"); //给表格的奇数行添加背景颜色
tb.find("tr:gt(1)").hover(function() { //给表格的行添加鼠标滑过更改背景样式
$(this).addClass("hover");
}, function() {
$(this).removeClass("hover");
});
var strNums = '';
var pageIndex = parseInt(page.current), pageSize = parseInt(page.pageSize), totalPage = parseInt(str.total);
var start, end;
if (totalPage <= 10) {
start = 1;
end = totalPage;
}
else {
if (pageIndex <= 10) {
start = 1;
end = 10;
}
else if (pageIndex > 10 && pageIndex > Math.floor(totalPage / 10) * 10) {
start = Math.floor(totalPage / 10) * 10 + 1;
end = totalPage;
} else if (pageIndex > 10 && pageIndex <= Math.floor(totalPage / 10) * 10) {
start = Math.floor((pageIndex - 1) / 10) * 10 + 1;
end = start + 9;
}
}
for (var i = start; i <= end; i++) {
i == pageIndex ? strNums += '<a href="javascript:void(0)" class="current">' + i + '</a>' : strNums += '<a href="javascript:void(0)">' + i + '</a>';
}
var strPrev = pageIndex == 1 ? '<div><a href="javascript:void(0)" class="btnText firstPage disable">首页</a><a href="javascript:void(0)" class="btnText prev disable">上一页</a>' : '<div><a href="javascript:void(0)" class="btnText firstPage">首页</a><a href="javascript:void(0)" class="btnText prev">上一页</a>';
var strNext = pageIndex == totalPage ? '<a href="javascript:void(0)" class="btnText next disable">下一页</a><a href="javascript:void(0)" class="btnText disable">尾页</a></div>' : '<a href="javascript:void(0)" class="btnText next">下一页</a><a href="javascript:void(0)" class="btnText lastPage">尾页</a></div>'

//alert(strPrev);
//alert(strNums);
//alert(strNext);

var $pageBtns = $(".pageBtns"); $pageBtns.html("");

var $btnHtml = $(strPrev + strNums + strNext);

$btnHtml.appendTo($pageBtns);

$btnHtml.find("a:not(.btnText)").click(function() { //给导航的 上一页,下一页,首页,尾页及数字链接添加点击事件
$(this).addClass("current").siblings().removeClass("current");
page.loadPage(parseInt($(this).html()));
}).siblings(".prev").click(function() { //上一页
if (page.current <= 1) { //如果是小于第一页,则上一页按钮点击将不执行任何操作
return false;
}
$(this).siblings(".current").removeClass("current").prev("a").addClass("current");
page.loadPrevPage();
}).siblings(".next").click(function() { //下一页
if (page.current >= totalPage) { //如果是大于或等于最大页码,则下一页按钮也不执行任何操作
return false;
}
$(this).siblings(".current").removeClass("current").next("a").addClass("current");
page.loadNexPage();
}).siblings(".firstPage").click(function() { //首页
page.loadPage(1);
}).siblings(".lastPage").click(function() { //尾页
page.loadPage(totalPage);
});

};
</script>
</head>
<body>
<table id="Citys" cellpadding="0" cellspacing="0" border="0" align="center">
<!--
<tr class="thead">
<th colspan="4">中国主要城市一览</th>
</tr>
<tr>
<th style="width:80px">编号</th><th>城市编号</th><th>城市名称</th><th>所属区域编号</th>
</tr>
<tr>
<td>1</td><td>001201</td><td>南昌</td><td>001200</td>
</tr>
-->
</table>
<div class="pageBtns"></div>
</body>
</html>

下面是模拟点击数据行的效果(没做处理,只是用 alert弹出)

还要注意的一点是行的单击事件 onclick="selectName(&quot;'+str.rows[i].City......

&quot;就是双引号实体,因为这里用了3次引号(外层单引号,两次双引号,所以双引号要转换下)



 

 

 

 

 

posted @ 2011-12-16 17:04  漫漫江雪  阅读(1593)  评论(2编辑  收藏  举报