asp.net jquery jason Efficient Transfer of data _ practical Tips
Last Update:2017-01-19
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 ">
<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>
<body>
<div>
<div>
<br/>
<input id= "The" "type=" button "value=" << "/><input id=" Previous "type=" button "
Value= "<"/><input id= "Next" type= "button" value= ">"/><input "Last" id= "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" >
Ship Date
</span>/
<span id= "Shippedname" >
Shipper Name
</span>/
<span id= "Shippedaddress" >
Shipper Address
</span>/
<span id= "Shippedcity" >
Shippers 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>
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>
Summary description of $codebehindclassname $
</summary>
[WebService (Namespace = "http://tempuri.org/json/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
public class Handler:ihttphandler
{
String dbfile = configurationmanager.appsettings["conn"]. ToString ();
readonly int PageSize = Int. Parse (configurationmanager.appsettings["PageSize"]);
public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
Do not allow the browser to cache
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 by OrderID Desc";
Else
sql = "SELECT top" + pagesize.tostring () + "* from to Orders where OrderID not in (select Top" + (PageIndex-1) * Pagesiz e). ToString () + "OrderID from Orders 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
Ajax method gets the data and displays 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",//background address to access
Data: "pageindex=" + pageindex,//to send
Complete:function () {$ ("#load"). Hide ();},//ajax hidden loading prompt when the request completes
Success:function (msg) {//msg for returned data, do data binding 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"). HTML ("<a href=orderinfo.aspx?id=" + N.orderid + &pageindex= "+pageindex+" > more</a > ");
ROW.ATTR ("id", "Ready");//change the ID of the row that binds the data
Row.appendto ("#datas");//Add to Template's container
});
$ ("[@id =ready]"). Show ();
Setpageinfo ();
}
});
}
function ChangeDate (date)
{
Return Date.replace ("-", "/"). Replace ("-", "/");
}
Set page/Total page information
function Setpageinfo ()
{
$ ("#pageinfo"). HTML (PageIndex + "/" + PageCount);
}
Ajax method to get total paging
function Getpagecount ()
{
$.ajax ({
Type: "Get",
DataType: "Text",
URL: "Handler.ashx",
Data: "Getpagecount=1",
Async:false,
Success:function (msg) {
$ ("#pagecount"). Val (msg);
}
});
}
Change the page button status
function Changestate (STATE1,STATE2)
{
if (state1 = 1)
{
document.getElementById ("a") disabled = "";
document.getElementById ("previous"). Disabled = "";
}
else if (state1 = 0)
{
document.getElementById ("a") 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 Total Paging
PageCount = parseint ($ ("#pagecount"). Val ());//total number of paging in variable PageCount
$ ("#load"). Hide ()//hidden loading hint
$ ("#template"). Hide ();//Hidden template
Changestate (0,1);//Set the initial state of the paging button
Bind ();//Bind the first page of data
First Page button click event
$ ("#first"). Click (function () {
PageIndex = 1;
Changestate (0,1);
Bind ();
});
Previous Page button click 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);
});
Last page button click event
$ ("#last"). Click (function () {
PageIndex = PageCount;
Changestate (1,0);
Bind (PageIndex);
});
});
Also need jquery-1.2.6.js online a lot
Add in Web.config
<appSettings>
<add key= "conn" value= "server=.; Database=northwind;uid=sa;pwd=sa "/>
<add key= "PageSize" value= "ten"/>
</appSettings>