本文講述的是如何利用 XMLHttpRequest 來對 Repeater 控件 進行無重新整理分頁。
實作的方式是,使用XMLHttpRequest對象異步向伺服器發送post 請求,傳遞設定好的每頁顯示記錄數,目前頁碼和記錄總數。伺服器端接收到請求時,根據參數從資料庫中查詢相應記錄,并通過Repeater 控件将資料顯示出來,然後調用Repeater 的RenderControl 方法 将Repeater 綁定後生成的HTML代碼作為伺服器端的響應文本傳回給用戶端,用戶端接到響應後替換Repeater 的相應HTML代碼,進而實作了Repeater 無重新整理分頁。
需要注意的地方:
1、顯示首頁記錄時,首頁和上一頁不可用,同理,顯示末頁記錄時,末頁和下一頁不可用。
2、重新設定每頁顯示記錄數時,要保持目前的頁碼不變,分頁數改變。
下面看代碼實作:
首先,建立一個WEB窗體,命名為 RepeaterDemo.aspx
代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterDemo.aspx.cs" Inherits="RepeaterDemo" %>
<head runat="server">
<title>無标題頁</title>
<style>
<!--
.n{TEXT-DECORATION:none;cursor:pointer} a{color:black} a:hover{color:blue}
.m{TEXT-DECORATION:none;cursor:default} a{color:black}
//-->
</style>
<script type="text/javascript">
var xmlHttp=null;
var index,size="10";
function $(id)
{
return document.getElementById(id);
}
function createXMLHttpRequest()
if(xmlHttp == null){
if(window.XMLHttpRequest) {
//Mozilla 浏覽器
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
// IE浏覽器
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('建立失敗');
}
}
}
}
function openAjax(para)
{
if( xmlHttp == null)
{
createXMLHttpRequest();
if( xmlHttp == null)
{
alert('出錯');
return ;
}
xmlHttp.open("post","RepeaterDemoResult.aspx?date="+new Date().getTime(),true);
xmlHttp.onreadystatechange=xmlHttpChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(para);
function xmlHttpChange()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
$('resultDiv').innerHTML=xmlHttp.responseText;
$('<%=lblCurrentPage.ClientID %>').innerText=index==null?$('<%=lblCurrentPage.ClientID %>').innerText:index;
if(index==1)
{
$('<%=lbtnFirst.ClientID %>').disabled=true;
$('<%=lbtnPrevious.ClientID %>').disabled=true;
$('<%=lbtnFirst.ClientID %>').className='m';
$('<%=lbtnPrevious.ClientID %>').className='m';
else
$('<%=lbtnFirst.ClientID %>').disabled='';
$('<%=lbtnPrevious.ClientID %>').disabled='';
$('<%=lbtnFirst.ClientID %>').className='n';
$('<%=lbtnPrevious.ClientID %>').className='n';
if(index==document.getElementById('<%=lblPageCount.ClientID %>').innerText)
$('<%=lbtnNext.ClientID %>').disabled=true;
$('<%=lbtnLast.ClientID %>').disabled=true;
$('<%=lbtnNext.ClientID %>').className='m';
$('<%=lbtnLast.ClientID %>').className='m';
$('<%=lbtnNext.ClientID %>').disabled=false;
$('<%=lbtnLast.ClientID %>').disabled=false;
$('<%=lbtnNext.ClientID %>').className='n';
$('<%=lbtnLast.ClientID %>').className='n';
function getHTML(operate)
if(event.srcElement.disabled)
{
return;
var currentPage;
var pageSize=$('<%=txtPageSize.ClientID %>').value;
var count=$('<%=lblCount.ClientID %>').innerText;
if(operate=='f')
currentPage=1;
else if(operate=='p')
currentPage=parseInt($('<%=lblCurrentPage.ClientID %>').innerText)-1;
else if(operate=='n')
currentPage=parseInt($('<%=lblCurrentPage.ClientID %>').innerText)+1;
else if(operate=='l')
currentPage=$('<%=lblPageCount.ClientID %>').innerText;
else if(operate=='c')
currentPage=$('<%=lblCurrentPage.ClientID %>').innerText;
if(pageSize==size)
size=pageSize;
else
return ;
}
index=currentPage;
var para="pageNum="+currentPage+"&pageSize="+pageSize+"&count="+count;
openAjax(para);
function verify()
{
if(isNaN(parseInt($('<%=txtPageSize.ClientID %>').value)))
alert('請輸入數字!');
return false;
}
getHTML('c');
var count=parseInt($('<%=lblCount.ClientID %>').innerText);
if(isNaN(count))
var pageCount=(count%size==0)?count/size:(count-(count%size))/size+1;
$('<%=lblPageCount.ClientID %>').innerText=pageCount;
var temp=parseInt($('<%=lblCurrentPage.ClientID %>').innerText);
if(pageCount<temp)
$('<%=lblCurrentPage.ClientID %>').innerText=pageCount;
index=pageCount;
</script>
</head>
<body>
<form id="form1" runat="server">
<div id='resultDiv' style="cursor:auto">
<asp:Repeater ID="rp" runat="server">
<HeaderTemplate>
<table><tr><td>編号</td><td>名稱</td><td>價格</td><td>庫存</td></tr>
</HeaderTemplate>
<AlternatingItemTemplate><tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr></AlternatingItemTemplate>
<ItemTemplate><tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr></ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
每頁顯示<asp:TextBox ID="txtPageSize" runat="server" Text="10"></asp:TextBox>條記錄&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="設定" onclick="return verify();" /><br />
記錄總數為:<asp:Label ID="lblCount" runat="server"></asp:Label>&nbsp;&nbsp;
共分<asp:Label ID="lblPageCount" runat="server"></asp:Label>頁&nbsp;&nbsp;
目前為第<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>頁<br />
<asp:LinkButton ID="lbtnFirst" CssClass='n' OnClientClick="getHTML('f');return false;" Text="首頁" runat="server"></asp:LinkButton>
<asp:LinkButton ID="lbtnPrevious" CssClass='n' OnClientClick="getHTML('p');return false;" Text="上頁" runat="server"></asp:LinkButton>
<asp:LinkButton ID="lbtnNext" CssClass='n' OnClientClick="getHTML('n');return false;" Text="下頁" runat="server"></asp:LinkButton>
<asp:LinkButton ID="lbtnLast" CssClass='n' OnClientClick="getHTML('l');return false;" Text="末頁" runat="server"></asp:LinkButton>
</form>
</body>
</html>
.cs 代碼
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Text;
public partial class RepeaterDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
using (SqlConnection con=new SqlConnection("server=.;uid=sa;pwd=sa;database=Northwind"))
SqlDataAdapter sda = new SqlDataAdapter("select count(*) from products", con);
DataSet ds = new DataSet();
sda.Fill(ds, "productsCount");
lblCount.Text = ds.Tables["productsCount"].Rows[0][0].ToString();
sda = new SqlDataAdapter("select * from products", con);
int count, pageCount, pageSize,currentPage;
int.TryParse(txtPageSize.Text, out pageSize);
pageSize = pageSize == 0 ? 10 : pageSize;
int.TryParse(lblCount.Text, out count);
pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
lblPageCount.Text = pageCount.ToString();
sda.Fill(ds, 0, pageSize, "products");
lblCurrentPage.Text = "1";
currentPage = 1;
rp.DataSource = ds.Tables["products"].DefaultView;
rp.DataBind();
//lbtnFirst.Enabled = false;
//lbtnPrevious.Enabled = false;
StringBuilder sb = new StringBuilder();
sb.Append("document.getElementById('" + lbtnFirst.ClientID + "').disabled=true;");
sb.Append("document.getElementById('" + lbtnPrevious.ClientID + "').disabled=true;"); if (pageCount == currentPage)
//lbtnNext.Enabled = false;
//lbtnLast.Enabled = false;
sb.Append("document.getElementById('" + lbtnNext.ClientID + "').disabled=true;");
sb.Append("document.getElementById('" + lbtnLast.ClientID + "').disabled=true;");
}//end if block
ClientScript.RegisterStartupScript(GetType(), "disabled", "<script>" + sb.ToString() + "</script>");
}//end using block
}//end if block
}//end Page_Load event
}
然後建立伺服器端接收XMLHttpRequest 請求的檔案,這裡用的是WEB窗體,命名為 RepeaterDemoResult.aspx
.aspx 代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterDemoResult.aspx.cs" Inherits="RepeaterDemoResult" %>
<form id="form1" runat="server">
<asp:Repeater ID="rp" runat="server">
<table><tr><td>編号</td><td>名稱</td><td>價格</td><td>庫存</td></tr>
<AlternatingItemTemplate>
<tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr>
</AlternatingItemTemplate>
<ItemTemplate>
</ItemTemplate>
</table>
</asp:Repeater>
.cs 代碼如下:
using System.IO;
public partial class ajax_xmlHttpRequest_RepeaterDemoResult : System.Web.UI.Page
using (SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=sa;database=Northwind"))
SqlDataAdapter sda = new SqlDataAdapter("select * from products", con);
DataSet ds = new DataSet();
int count, pageSize, currentPage;
int.TryParse(Request.Form["pageSize"], out pageSize);
pageSize = pageSize == 0 ? 10 : pageSize;
int.TryParse(Request.Form["count"], out count);
int.TryParse(Request.Form["pageNum"], out currentPage);
int tempCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
if (tempCount < currentPage)
currentPage = tempCount;
sda.Fill(ds, (currentPage - 1) * pageSize, pageSize, "products");
rp.DataSource = ds.Tables["products"].DefaultView;
rp.DataBind();
Response.Clear();
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
rp.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}