DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> AJAX分頁的代碼(後台asp.net)
AJAX分頁的代碼(後台asp.net)
編輯:JQuery特效代碼     
在ASP.NET 中有很多數據展現的控件,比如用的最多的GridView,它同時也自帶了分頁的功能。但是我們知道用GridView來顯示數據,如果沒有禁用ViewState,頁面的大小會是非常的大的。而且平時我們點擊首頁,下一頁,上一頁,尾頁這些功能都是會引起頁面回發的,也就是需要完全跟服務器進行交互,來回響應的時間,傳輸的數據量都是很大的。AJAX的分頁可以很好的解決這些問題。
開發的壞境是:jQuery AJAX+Northwind。
具體的步驟:
SearchCustomer.aspx:
代碼如下:
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
var pageIndex = 0;
var pageSize = 10;
$(function () {
$("#btnSearch").click(function () {
/*
name 顧客的名字, 文本框中輸入的內容
0 表示的是第1頁
10 每頁的大小
*/
var name = $("#txtSearch").val();
pageIndex = 0;
AjaxGetData(name, pageIndex, pageSize);
});
});
function AjaxGetData(name, index, size) {
$.ajax({
url: "jQueryPaging.aspx",
type: "Get",
data: "Name=" + name + "&PageIndex=" + index + "&PageSize=" + size,
dataType: "json",
success: function (data) {
var htmlStr = "";
htmlStr += "<table>"
htmlStr += "<thead>"
htmlStr += "<tr><td>CustomerID</td><td>CompanyName</td><td>ContactName</td><td>ContactTitle</td><td>Address</td><td>City</td></tr>"
htmlStr += "</thead>";
htmlStr += "<tbody>"
for (var i = 0; i < data.Customers.length; i++) {
htmlStr += "<tr>";
htmlStr += "<td>" + data.Customers[i].CustomerID + "</td>"
+ "<td>" + data.Customers[i].CompanyName + "</td>"
+ "<td>" + data.Customers[i].ContactName + "</td>"
+ "<td>" + data.Customers[i].ContactTitle + "</td>"
+ "<td>" + data.Customers[i].Address + "</td>"
+ "<td>" + data.Customers[i].City + "</td>"
htmlStr += "</tr>";
}
htmlStr += "</tbody>";
htmlStr += "<tfoot>";
htmlStr += "<tr>";
htmlStr += "<td colspan='6'>";
htmlStr += "<span>共有記錄" + data.Count + ";共<span id='count'>" + (data.Count % 10 == 0 ? parseInt(data.Count / 10) : parseInt(data.Count / 10 + 1)) + "</span>頁" + "</span>";
htmlStr += "<a href='javascript:void' onclick='GoToFirstPage()' id='aFirstPage' >首 頁</a> ";
htmlStr += "<a href='javascript:void' onclick='GoToPrePage()' id='aPrePage' >前一頁</a> ";
htmlStr += "<a href='javascript:void' onclick='GoToNextPage()' id='aNextPage'>後一頁</a> ";
htmlStr += "<a href='javascript:void' onclick='GoToEndPage()' id='aEndPage' >尾 頁</a> ";
htmlStr += "<input type='text' /><input type='button' value='跳轉' onclick='GoToAppointPage(this)' /> ";
htmlStr += "</td>";
htmlStr += "</tr>";
htmlStr += "</tfoot>";
htmlStr += "</table>";
$("#divSearchResult").html(htmlStr);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
}
//首頁
function GoToFirstPage() {
pageIndex = 0;
AjaxGetData($("#txtSearch").val(), pageIndex, pageSize);
}
//前一頁
function GoToPrePage() {
pageIndex -= 1;
pageIndex = pageIndex >= 0 ? pageIndex : 0;
AjaxGetData($("#txtSearch").val(), pageIndex, pageSize);
}
//後一頁
function GoToNextPage() {
if (pageIndex + 1 < parseInt($("#count").text())) {
pageIndex += 1;
}
AjaxGetData($("#txtSearch").val(), pageIndex, pageSize);
}
//尾頁
function GoToEndPage() {
pageIndex = parseInt($("#count").text()) - 1;
AjaxGetData($("#txtSearch").val(), pageIndex, pageSize);
}
//跳轉
function GoToAppointPage(e) {
var page = $(e).prev().val();
if (isNaN(page)) {
alert("請輸入數字!");
}
else {
var tempPageIndex = pageIndex;
pageIndex = parseInt($(e).prev().val())-1;
if (pageIndex < 0 || pageIndex >= parseInt($("#count").text())) {
pageIndex = tempPageIndex;
alert("請輸入有效的頁面范圍!");
}
else {
AjaxGetData($("#txtSearch").val(), pageIndex, pageSize);
}
}
}
</script>

數據的傳輸用的JSON格式。大家知道JSON是輕量級別的數據傳輸。前台的展現時用的table。這樣生成的HTML代碼很簡潔。
HTML如下:
代碼如下:
<div>
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" />
</div>
<div id="divSearchResult">
</div>

jQueryPaging.aspx頁面的CS代碼如下:
代碼如下:
public partial class jQueryPaging : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Int32 pageIndex=Int32.MinValue;
Int32 pageSize=Int32.MinValue;
String name=String.Empty;
JavaScriptSerializer jss=new JavaScriptSerializer();
if(Request["Name"]!=null)
{
name=Request["Name"].ToString();
if (Request["PageIndex"] != null)
{
pageIndex = Int32.Parse(Request["PageIndex"].ToString());
pageSize = Request["PageSize"] != null ? Int32.Parse(Request["PageSize"].ToString()) : 10;
IList<Customer> customersLists = new List<Customer>();
Customer c = null;
DataSet ds= LookDataFromDB(name,pageIndex,pageSize);
foreach (DataRow row in ds.Tables[0].Rows)
{
c = new Customer();
c.CustomerID = row["CustomerID"].ToString();
c.CompanyName = row["CompanyName"].ToString();
c.ContactName = row["ContactName"].ToString();
c.ContactTitle = row["ContactTitle"].ToString();
c.Address = row["Address"].ToString();
c.City = row["City"].ToString();
customersLists.Add(c);
}
if (customersLists.Count>0)
{
Response.Write("{\"Count\":"+ds.Tables[1].Rows[0][0]+",\"Customers\":"+jss.Serialize(customersLists)+"}");
Response.End();
}
}
}
}
private DataSet LookDataFromDB(string name, int pageIndex, int pageSize)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchCustomerByName";
cmd.Parameters.Add(new SqlParameter("@name",name));
cmd.Parameters.Add(new SqlParameter("@pageIndex",pageIndex));
cmd.Parameters.Add(new SqlParameter("@pageSize", pageSize));
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
dataAdapter.Fill(ds);
}
catch (Exception)
{
}
finally
{
if (dataAdapter != null)
{
dataAdapter.Dispose();
}
if (cmd != null)
{
cmd.Dispose();
}
if (conn != null)
{
conn.Dispose();
}
}
return ds;
}
}

還有我們在CS中定義的Model類:
代碼如下:
public class Customer
{
public String CustomerID { get; set; }
public String CompanyName { get; set; }
public String ContactName { get;set;}
public String ContactTitle { get; set; }
public String Address { get; set; }
public String City { get; set; }
}
SearchCustomerByName 存儲過程的代碼如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE SearchCustomerByName
@name nvarchar(30),
@pageIndex int,
@pageSize int
AS
BEGIN
SET NOCOUNT ON;
select t.CustomerID,t.CompanyName,t.ContactName,t.ContactTitle,t.Address,t.City from
(
select Row_Number() over (order by CustomerID) AS RowNum,* from Customers where ContactName like '%'+@name+'%'
) t
where t.RowNum between @pageIndex*10+1 and (@pageIndex+1)*10
select count(*) from Customers
where ContactName like '%'+@name+'%'
END
GO

具體的效果,大家可以把上述的代碼響應的復制到VS中和數據庫中,進行演示。
這個版本其實很多的功能點都是沒有考慮到的,僅僅是個示例,大家可以在自己的實際項目中修改以上的功能來滿足自己的需求。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved