AJAX paging code (backend asp.net)

Source: Internet
Author: User

There are many data display controls in ASP. NET, such as the most commonly used GridView, which also comes with the paging function. However, we know that using the GridView to display data, if ViewState is not disabled, the page size will be very large. In addition, when we click the home page, next page, previous page, and last page, these functions will cause page sending back, that is, the time for completely interacting with the server and responding back and forth, the amount of data transmitted is large. AJAX paging can effectively solve these problems.
The development environment is jQuery AJAX + Northwind.
Specific steps:
SearchCustomer. aspx:
Copy codeThe Code is as follows:
<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: the name of the customer. The content entered in the text box
0 indicates 1st pages
10 page size
*/
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. MERs. length; I ++ ){
HtmlStr + = "<tr> ";
HtmlStr + = "<td>" + data. MERs [I]. CustomerID + "</td>"
+ "<Td>" + data. MERs [I]. CompanyName + "</td>"
+ "<Td>" + data. MERs [I]. ContactName + "</td>"
+ "<Td>" + data. MERs [I]. ContactTitle + "</td>"
+ "<Td>" + data. MERs [I]. Address + "</td>"
+ "<Td>" + data. MERs [I]. City + "</td>"
HtmlStr + = "</tr> ";
}
HtmlStr + = "</tbody> ";
HtmlStr + = "<tfoot> ";
HtmlStr + = "<tr> ";
HtmlStr + = "<td colspan = '6'> ";
HtmlStr + = "<span> total records" + data. Count + "; Total <span id = 'Count'>" + (data. count % 10 = 0? ParseInt (data. Count/10): parseInt (data. Count/10 + 1) + "</span> page" + "</span> ";
HtmlStr + = "<a href = 'javascript: void' onclick = 'gotofirstpage () 'id = 'afirstpage'> first page </a> ";
HtmlStr + = "<a href = 'javascript: void' onclick = 'gotoprepage () 'id = 'aprepage'> previous page </a> ";
HtmlStr + = "<a href = 'javascript: void' onclick = 'gotonextpage () 'id = 'anextpage'> next page </a> ";
HtmlStr + = "<a href = 'javascript: void' onclick = 'gotoendpage () 'id = 'endpage'> last page </a> ";
HtmlStr + = "<input type = 'text'/> <input type = 'button 'value = 'jump to 'onclick = 'gotoappointpage (this)'/> ";
HtmlStr + = "</td> ";
HtmlStr + = "</tr> ";
HtmlStr + = "</tfoot> ";
HtmlStr + = "</table> ";
$ ("# DivSearchResult" pai.html (htmlStr );
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert (XMLHttpRequest );
Alert (textStatus );
Alert (errorThrown );
}
});
}
// Homepage
Function GoToFirstPage (){
PageIndex = 0;
AjaxGetData ($ ("# txtSearch"). val (), pageIndex, pageSize );
}
// Previous Page
Function GoToPrePage (){
PageIndex-= 1;
PageIndex = pageIndex> = 0? PageIndex: 0;
AjaxGetData ($ ("# txtSearch"). val (), pageIndex, pageSize );
}
// Next page
Function GoToNextPage (){
If (pageIndex + 1 <parseInt ($ ("# count"). text ())){
PageIndex + = 1;
}
AjaxGetData ($ ("# txtSearch"). val (), pageIndex, pageSize );
}
// Last page
Function GoToEndPage (){
PageIndex = parseInt ($ ("# count"). text ()-1;
AjaxGetData ($ ("# txtSearch"). val (), pageIndex, pageSize );
}
// Jump
Function GoToAppointPage (e ){
Var page = $ (e). prev (). val ();
If (isNaN (page )){
Alert ("enter a number! ");
}
Else {
Var tempPageIndex = pageIndex;
PageIndex = parseInt ($ (e). prev (). val ()-1;
If (pageIndex <0 | pageIndex> = parseInt ($ ("# count"). text ())){
PageIndex = tempPageIndex;
Alert ("enter a valid page range! ");
}
Else {
AjaxGetData ($ ("# txtSearch"). val (), pageIndex, pageSize );
}
}
}
</Script>

The data is transmitted in JSON format. JSON is a lightweight data transmission. Table used for front-end display. The generated HTML code is concise.
The HTML is as follows:
Copy codeThe Code is as follows:
<Div>
<Input type = "text" id = "txtSearch"/>
<Input type = "button" id = "btnSearch" value = "Search"/>
</Div>
<Div id = "divSearchResult">
</Div>

The CS code of the jQueryPaging. aspx page is as follows:
Copy codeThe Code is as follows:
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] + ", \" MERs \ ":" + 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;
}
}

We also define the Model class in CS:
Copy codeThe Code is as follows:
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 ;}
}
The code for the SearchCustomerByName stored procedure is as follows:
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 MERs where ContactName like '%' + @ name + '%'
) T
Where t. RowNum between @ pageIndex * 10 + 1 and (@ pageIndex + 1) * 10
Select count (*) from MERs
Where ContactName like '%' + @ name + '%'
END
GO

For specific results, you can copy the above Code response to VS and the database for demonstration.
In fact, many features of this version are not taken into account. It is just an example. You can modify the above functions in your own project to meet your needs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.