.net用ajax技术实现无刷新分页(初学)
在这里我们将用存储过程实现数据的分页,代码如下:
----胡耀华 2007.4.4
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[PageCut]
@strGetFields varchar(1000) = '*', -- 需要返回的列
@fldName varchar(255)='', -- 排序的字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@strWhere varchar(1500) = '' ,-- 查询条件 (注意: 不要加 where)
@Counts int out -- 返回记录总数, 非 0 值则返回 这里作运行后返回的记录总数分页用
AS
set nocount on
declare @strSQL varchar(5000) -- 主语句
declare @CountSQL nVarchar(4000)
declare @strTmp varchar(110) -- 临时变量
declare @strOrder varchar(400) -- 排序类型
if @PageIndex = 1
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +@strGetFields+ ' from TestTable where ' + @strWhere + ' ' + ' order by [' + @fldName +'] desc'
else
set @strSQL = 'select top ' + str(@PageSize) +@strGetFields+ ' from TestTable '+ ' order by [' + @fldName +'] desc'
--如果是第一页就执行以上代码,这样会加快执行速度
end
else
begin
--以下代码赋予了@strSQL以真正执行的SQL代码
--set @strTmp = '<(select min'
set @strSQL = 'select top ' + str(@PageSize) +@strGetFields+ ' from TestTable where [' + @fldName + ']' + '<(select min'+ '(['+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldName + '] from TestTable ' + ' order by [' + @fldName +'] desc'+ ') as tblTmp)'+ ' order by [' + @fldName +'] desc'
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from TestTable where [' + @fldName + ']' + '<(select min' + '([' + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' [' + @fldName + '] from TestTable where ' + @strWhere + ' order by [' + @fldName +'] desc' + ') as tblTmp) and ' + @strWhere + ' ' + ' order by [' + @fldName +'] desc'
end
if @strWhere != ''
set @CountSQL='select @Counts=count(*) from TestTable where ' + @strWhere +''
else
set @CountSQL='select @Counts=count(*) from TestTable '
exec sp_executesql @CountSQL, N'@Counts int out ',@Counts out
exec ( @strSQL)
set nocount off
这个是我根据现在网上所收集通用存储过程所改写的,效率不错适合百万级数据的分页。
那下一步。我们先建立一个web项目,建立一个数据库连接类db.cs,代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// db 的摘要说明
/// </summary>
public class db
{
public db()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
//public SqlConnection Conn()
//{
// SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);//连接数据库
// return conn;
//}
//返回DATASET
public static DataSet sta()
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);//连接数据库
conn.Open();
//SqlCommand com = new SqlCommand("PageCut", conn); com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter MyCommand = new SqlDataAdapter("PageCut", conn);
//SqlDataReader dbr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter strGetFields = new SqlParameter("@strGetFields",SqlDbType.VarChar);
strGetFields. = "*";//字段
MyCommand.SelectCommand.Parameters.Add(strGetFields);
SqlParameter fldName = new SqlParameter("@fldName",SqlDbType.VarChar);
fldName. = "id";//排序字段
MyCommand.SelectCommand.Parameters.Add(fldName);
SqlParameter PageSize = new SqlParameter("@PageSize",SqlDbType.Int);
PageSize. = 10;//每页大小
MyCommand.SelectCommand.Parameters.Add(PageSize);
SqlParameter PageIndex = new SqlParameter("@PageIndex",SqlDbType.Int);
PageIndex. =1;//当前页
MyCommand.SelectCommand.Parameters.Add(PageIndex);
SqlParameter strWhere = new SqlParameter("@strWhere",SqlDbType.VarChar);
strWhere. = "";//条件
MyCommand.SelectCommand.Parameters.Add(strWhere);
SqlParameter Counts = new SqlParameter("@Counts",SqlDbType.Int);
Counts. = 1;//总记录数
Counts.Direction = ParameterDirection.Output;//因为这里要返回,所以要设置一下,返回计算过后的结果
MyCommand.SelectCommand.Parameters.Add(Counts);
MyCommand.Fill(ds);
return ds;
}
public static SqlDataAdapter dt(int Pagesize)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);//连接数据库
conn.Open();
//SqlCommand com = new SqlCommand("PageCut", conn); com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter MyCommand = new SqlDataAdapter("PageCut", conn);
//SqlDataReader dbr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter strGetFields = new SqlParameter("@strGetFields", SqlDbType.VarChar);
strGetFields. = "*";//字段
MyCommand.SelectCommand.Parameters.Add(strGetFields);
SqlParameter fldName = new SqlParameter("@fldName", SqlDbType.VarChar);
fldName. = "id";//排序字段
MyCommand.SelectCommand.Parameters.Add(fldName);
SqlParameter PageSize = new SqlParameter("@PageSize", SqlDbType.Int);
PageSize. = 10;//每页大小
MyCommand.SelectCommand.Parameters.Add(PageSize);
SqlParameter PageIndex = new SqlParameter("@PageIndex", SqlDbType.Int);
PageIndex. = Pagesize;//当前页
MyCommand.SelectCommand.Parameters.Add(PageIndex);
SqlParameter strWhere = new SqlParameter("@strWhere", SqlDbType.VarChar);
strWhere. = "";//条件
MyCommand.SelectCommand.Parameters.Add(strWhere);
SqlParameter Counts = new SqlParameter("@Counts", SqlDbType.Int);
Counts. = 1;//总记录数
Counts.Direction = ParameterDirection.Output;//因为这里要返回,所以要设置一下,返回计算过后的结果
MyCommand.SelectCommand.Parameters.Add(Counts);
conn.Close();
return MyCommand;
}
public static SqlDataReader sdr(int Pagesize)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);//连接数据库
conn.Open();
SqlCommand com = new SqlCommand("PageCut", conn);
com.CommandType = CommandType.StoredProcedure;
SqlParameter strGetFields = new SqlParameter("@strGetFields", SqlDbType.VarChar);
strGetFields. = "*";//字段
com.Parameters.Add(strGetFields);
SqlParameter fldName = new SqlParameter("@fldName", SqlDbType.VarChar);
fldName. = "id";//排序字段
com.Parameters.Add(fldName);
SqlParameter PageSize = new SqlParameter("@PageSize", SqlDbType.Int);
PageSize. = 10;//每页大小
com.Parameters.Add(PageSize);
SqlParameter PageIndex = new SqlParameter("@PageIndex", SqlDbType.Int);
PageIndex. = Pagesize;//当前页
com.Parameters.Add(PageIndex);
SqlParameter strWhere = new SqlParameter("@strWhere", SqlDbType.VarChar);
strWhere. = "";//条件
com.Parameters.Add(strWhere);
SqlParameter Counts = new SqlParameter("@Counts", SqlDbType.Int);
Counts. = 1;//总记录数
Counts.Direction = ParameterDirection.Output;//因为这里要返回,所以要设置一下,返回计算过后的结果
com.Parameters.Add(Counts);
SqlDataReader sdr =com.ExecuteReader();
return sdr;
}
public static SqlDataReader sdr()
{
throw new Exception("The method or operation is not implemented.");
}
}
建立一个.aspx页(Default.aspx)调用db.cs类:
public partial class _Default : System.Web.UI.Page
{
db db = new db();
public string qq;
public int pageze=1;
public int temp;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getveiw(1);
next();
}
}
// public override void VerifyRenderingInServerForm(Control control)
// {
// Confirms that an HtmlForm control is rendered for
// }
public void next()
{
if (Request.QueryString["next"] == "next")
{
temp = Convert.ToInt32(Request.QueryString["name"]);
getveiw(temp);
}
}
public void getveiw(int pagesize)
{
SqlDataAdapter sta = db.dt(pagesize);
DataSet ds=new DataSet();
sta.Fill(ds);
GridView1.DataSource=ds;
this.GridView1.DataBind();
}
在这里为了方便我们姑且用gridview来绑定数据(我们也可以将数据以XML文档存储)。建立一个HTML新页(HTMLPage.htm)用AJAX技术调用.aspx页。XMLHttpRequest提供了两个用来访问服务器响应的属性:responseText和responseXML。在这里由于我运用gridview存储数据。所以我们运用responseText属性(它返回的是一个串,即html串)。假如我们运用XML来存储数据的话,那我们应该用responseXML属性了。好了.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>
< type="text/java">
var xmlHttp
var page
crrate()
{
if(ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if (XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
//初始化为第一页
star()
{page=1;
crrate()
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET","Default.aspx",true)
xmlHttp.send(null)
}
//下一页
next()
{page=page+1
str= getElementById("Text1").;
getElementById("txtHint").innerHTML="";
var url="Default.aspx?next=next&name="+page;
crrate();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null)
}
//跳转到某一页
go()
{
str= getElementById("Text1").;
page=str;
getElementById("txtHint").innerHTML="";
var url="Default.aspx?next=next&name="+page;
crrate();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null)
}
//上一页
prve()
{
page=page-1
str= getElementById("Text1").;
getElementById("txtHint").innerHTML="";
var url="Default.aspx?next=next&name="+page;
crrate();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null)
}
//解析服务器响应提供的串
stateChanged()
{
if (xmlHttp.readyState==4)
{if(xmlHttp.status==200){
getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
}
setInterval('star()');
</>
</head>
<body>
<div id="txtHint"></div>
</body>
<input id="Text1" type="text" style="width:20px"/><input id="Button3" type="button"
="go" ="go()"/><input id="Button1" type="button" ="下一页" ="next()"/><input
id="Button2" type="button" ="上一页" ="prve()" />
</html>
代码说明(关于ajax的知识点我就不细说了):url="Default.aspx?next=next&name="+page;将next=next&name="+page传给.aspx页其中page是要显示的页码。.aspx页接收后将运行: if (Request.QueryString["next"] == "next")
{
temp = Convert.ToInt32(Request.QueryString["name"]);
getveiw(temp);
}语句很简单。
这样一个简单的无刷新分页的实例就完成了。由于本人的JS水平有限,现在只能做到这了。当然还可以添加一些新的功能。这里我只是想将我的方法与大家分享。至于功能,待以后继续完善了!!!
ps:在网上还有很多方法。方法之一是将GRIDVIEW解析,运用它自身的分页技术来实现具体方法参阅:http://zfnh2002.bokee.com/viewdiary.12243206.html。此方法不适用因为GRIDVIEW自身的分页是将数据都取出后再分页,效率显然很低。还有一种方法是用.net的ajax架构(ajax.net或alax)来实现无刷新分页。这种方法最好,具体从baidu上搜一下会有N多方法的。