Efficient data transmission by jquery jason in asp.net

Source: Internet
Author: User

Default.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> test2 </title>
<Script src = "js/jquery-1.2.6.js" type = "text/javascript"> </script>
<Script src = "js/Gonneng. js" type = "text/javascript"> </script>
<Script src = "js/ajaxfn. js" type = "text/javascript"> </script>
</Head>
<Body>
<Div>
<Div>
<Br/>
<Input id = "first" type = "button" value = "<"/> <input id = "previous" type = "button"
Value = "<"/> <input id = "next" type = "button" value = ">"/> <input id = "last" type = "button"
Value = ">"/>
<Span id = "pageinfo"> </span>
<Ul id = "datas">
<Li id = "template">
<Span id = "OrderID">
Order ID
</Span>/
<Span id = "CustomerID">
Customer ID
</Span>
<Span id = "EmployeeID">
Employee ID
</Span>/
<Span id = "OrderDate">
Order Date
</Span>/
<Span id = "ShippedDate">
Date of shipment
</Span>/
<Span id = "ShippedName">
Owner name
</Span>/
<Span id = "ShippedAddress">
Cargo owner address
</Span>/
<Span id = "ShippedCity">
Cargo owner City
</Span>/
<Span id = "more">
More information
</Span>
</Li>
</Ul>
</Div>
<Div id = "load" style = "left: 0px; position: absolute; top: 0px; background-color: red">
LOADING ....
</Div>
<Input type = "hidden" id = "pagecount"/>
</Div>
</Body>
</Html>
Handler. ashx
<% @ WebHandler Language = "C #" Class = "jQueryJSON. Handler" %>
Using System;
Using System. Data;
Using System. Web;
Using System. Collections;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Configuration;
Using System. Data. SqlClient;
Using System. Text;
Using System. Xml;
Using NetServ. Net. Json;
Namespace jQueryJSON
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (Namespace = "http://tempuri.org/json/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
Public class Handler: IHttpHandler
{
String dbfile = ConfigurationManager. etettings ["conn"]. ToString ();
Readonly int PageSize = int. Parse (ConfigurationManager. receivettings ["PageSize"]);
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
// Disable browser caching
Context. Response. Buffer = true;
Context. Response. ExpiresAbsolute = DateTime. Now. AddDays (-1 );
Context. Response. AddHeader ("pragma", "no-cache ");
Context. Response. AddHeader ("cache-control ","");
Context. Response. CacheControl = "no-cache ";
String result = "";
If (context. Request. Params ["getPageCount"]! = Null) result = GetPageCount ();
If (context. Request. Params ["pageIndex"]! = Null)
{
String pageindex = context. Request. Params ["pageIndex"];
// If (context. Cache. Get (pageindex )! = Null)
// Result = context. Cache. Get (pageindex). ToString ();
// Else
//{
// Result = GetPageData (context. Request. Params ["pageIndex"]);
// Context. Cache. Add (
// Pageindex,
// Result,
// Null,
// DateTime. Now. AddMinutes (1 ),
// System. Web. Caching. Cache. NoSlidingExpiration,
// System. Web. Caching. CacheItemPriority. Default,
// Null );
//}
Result = GetPageData (context. Request. Params ["pageIndex"]);
}
Context. Response. Write (result );
}
Private string GetPageData (string p)
{
Int PageIndex = int. Parse (p );
String SQL;
If (PageIndex = 1)
SQL = "select top" + PageSize. ToString () + "* from Orders order by OrderID desc ";
Else
SQL = "select top" + PageSize. toString () + "* from Orders where OrderID not in (select top" + (PageIndex-1) * PageSize ). toString () + "OrderID from Orders order by OrderID desc) order by OrderID desc ";
SqlConnection conn = new SqlConnection (dbfile );
SqlDataAdapter da = new SqlDataAdapter (SQL, conn );
DataTable dt = new DataTable ("table ");
Da. Fill (dt );
Return DataTableJson (dt );
}
Private string GetPageCount ()
{
SqlConnection conn = new SqlConnection (dbfile );
SqlCommand cmd = new SqlCommand ("select count (*) from Orders", conn );
Conn. Open ();
Int rowcount = Convert. ToInt32 (cmd. ExecuteScalar ());
Conn. Close ();
Return (rowcount + PageSize-1)/PageSize). ToString ();
}
Private string DataTable2Json (DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder ();
JsonBuilder. Append ("{\"");
JsonBuilder. Append (dt. TableName );
JsonBuilder. Append ("\":[");
For (int I = 0; I <dt. Rows. Count; I ++)
{
JsonBuilder. Append ("{");
For (int j = 0; j <dt. Columns. Count; j ++)
{
JsonBuilder. Append ("\"");
JsonBuilder. Append (dt. Columns [j]. ColumnName );
JsonBuilder. Append ("\":\"");
JsonBuilder. Append (dt. Rows [I] [j]. ToString ());
JsonBuilder. Append ("\",");
}
JsonBuilder. Remove (jsonBuilder. Length-1, 1 );
JsonBuilder. Append ("},");
}
JsonBuilder. Remove (jsonBuilder. Length-1, 1 );
JsonBuilder. Append ("]");
JsonBuilder. Append ("}");
Return jsonBuilder. ToString ();
}
Private string DataTableJson (DataTable dt)
{
JsonWriter writer = new JsonWriter ();
JsonObject content = new JsonObject ();
JsonArray Orders = new JsonArray ();
JsonObject Order;
JsonObject OrderItem = new JsonObject ();
For (int I = 0; I <dt. Rows. Count; I ++)
{
Order = new JsonObject ();
For (int j = 0; j <dt. Columns. Count; j ++)
{
Order. Add (dt. Columns [j]. ColumnName, dt. Rows [I] [j]. ToString ());
}
Orders. Add (Order );
}
Content. Add (dt. TableName, Orders );
Content. Write (writer );
Writer = new IndentedJsonWriter ();
Content. Write (writer );
Return writer. ToString ();
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}
Ajaxfn. js
// Obtain data using the AJAX method and display it on the page
Function bind ()
{
$ ("[@ Id = ready]"). remove ();
$ ("# Load"). show ();
$. Ajax ({
Type: "get", // use the get method to access the background
DataType: "json", // return data in json format
Url: "Handler. ashx", // The background address to be accessed
Data: "pageIndex =" + pageIndex, // data to be sent
Complete: function () {$ ("# load"). hide () ;}, // hide the loading prompt when the AJAX request is complete
Success: function (msg) {// msg is the returned data. Bind The data here.
Var data = msg. table;
$. Each (data, function (I, n ){
Var row = $ ("# template"). clone ();
Row. find ("# OrderID"). text (n. OrderID );
Row. find ("# CustomerID"). text (n. CustomerID );
Row. find ("# EmployeeID"). text (n. EmployeeID );
Row. find ("# OrderDate"). text (ChangeDate (n. OrderDate ));
If (n. RequiredDate! = Undefined) row. find ("# ShippedDate"). text (ChangeDate (n. RequiredDate ));
Row. find ("# ShippedName"). text (n. ShipName );
Row. find ("# ShippedAddress"). text (n. ShipAddress );
Row. find ("# ShippedCity"). text (n. ShipCity );
Row. find ("# more" rows .html ("<a href = OrderInfo. aspx? Id = "+ n. OrderID +" & pageindex = "+ pageIndex +"> More </a> ");
Row. attr ("id", "ready"); // change the id of the row bound to the data.
Row. appendTo ("# datas"); // Add it to the template container
});
$ ("[@ Id = ready]"). show ();
SetPageInfo ();
}
});
}
Function ChangeDate (date)
{
Return date. replace ("-", "/"). replace ("-","/");
}
// Set the page number/total page number
Function SetPageInfo ()
{
$ ("# Pageinfo" pai.html (pageIndex + "/" + pageCount );
}
// Obtain the total number of pages by AJAX
Function GetPageCount ()
{
$. Ajax ({
Type: "get ",
DataType: "text ",
Url: "Handler. ashx ",
Data: "getPageCount = 1 ",
Async: false,
Success: function (msg ){
$ ("# Pagecount"). val (msg );
}
});
}
// Change the page flip button status
Function ChangeState (state1, state2)
{
If (state1 = 1)
{
Document. getElementById ("first"). disabled = "";
Document. getElementById ("previous"). disabled = "";
}
Else if (state1 = 0)
{
Document. getElementById ("first"). disabled = "disabled ";
Document. getElementById ("previous"). disabled = "disabled ";
}
If (state2 = 1)
{
Document. getElementById ("next"). disabled = "";
Document. getElementById ("last"). disabled = "";
}
Else if (state2 = 0)
{
Document. getElementById ("next"). disabled = "disabled ";
Document. getElementById ("last"). disabled = "disabled ";
}
}
Gonneng. js
Var pageIndex = 1
Var pageCount = 0;
$ (Function (){
GetPageCount (); // get the total number of pages
PageCount = parseInt ($ ("# pagecount"). val (); // put the total number of pages in the variable pageCount
$ ("# Load"). hide (); // hide the loading prompt
$ ("# Template"). hide (); // hide the template
ChangeState (); // sets the initial status of the page flip button.
Bind (); // bind the data on the first page
// Click the button on the first page
$ ("# First"). click (function (){
PageIndex = 1;
ChangeState (0, 1 );
Bind ();
});
// Click the previous page button event
$ ("# Previous"). click (function (){
PageIndex-= 1;
ChangeState (-1, 1 );
If (pageIndex <= 1)
{
PageIndex = 1;
ChangeState (0,-1 );
}
Bind ();
});
// Next page button click event
$ ("# Next"). click (function (){
PageIndex + = 1;
ChangeState (1,-1 );
If (pageIndex> = pageCount)
{
PageIndex = pageCount;
ChangeState (-1, 0 );
}
Bind (pageIndex );
});
// Button click event on the last page
$ ("# Last"). click (function (){
PageIndex = pageCount;
ChangeState (1, 0 );
Bind (pageIndex );
});
});
Also need jquery-1.2.6.js many online
Add in web. config
<Deleetask>
<Add key = "conn" value = "Server =.; database = Northwind; uid = sa; pwd = sa"/>
<Add key = "PageSize" value = "10"/>
</AppSettings>

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.