Asp.net code for transmitting and receiving DataTable using Jquery Ajax

Source: Internet
Author: User
Tags string back

This article introduces the asp.net code for transmitting and receiving DataTable using Jquery Ajax. The following is an example of how Ajax transfers and receives DataTable.

This article describes the asp tutorial. net code for transferring and receiving datatable using jquery ajax. The following is an example of how ajax transfers and receives datatable.

Asp.net tutorial code

Simple Example

Webservices:

[Webmethod (true)]
[Scriptmethod (responseformat = responseformat. xml)]
Public string competitor (string sl_id)
{
Dataset ds;
Slcompetitor = new slcompetitor ();
Ds = slcompetitor. getslcompetitor (int. parse (sl_id ));
Return ds. getxml ();
}

Js:
 

$. Ajax ({
Type: "post ",
Url: "../webservices/advquerycarwebservice. asmx/deciderdetai ",
Data: "{sl_id:" + sl_id + "}",
Datatype: "xml ",
Contenttype: "application/json ",
Error: function (data ){
Alert ("loading error, details:" + data. status + ">>>" + data. statustext );
},
Success: function (getxml ){
Tabledecider. removechild (tbodydecider );
$ (Getxml). find ("table"). each (function (I) {// xml directory id
Var name = $ (this). children ("stakeholder"). text (); // get text


Asp. netx File

Void ihttphandler. processrequest (httpcontext context)
{
// Context. response. contenttype = "text/json ";

Int bids = 0;
Int. tryparse (context. request. querystring ["bid"]. tostring (), out bids); // Project id

Int pid = 0;
Int. tryparse (context. request. querystring ["productid"]. tostring (), out pid); // product id

If (bids! = 0 & pid! = 0)
{
Datatable dt = logic. bidaddress. getbidaddresstobidandproductidlist (bids, pid );
If (dt. rows. count! = 0)
{
Using (jsonwriter jsont = new jsontextwriter (context. response. output ))
{
Jsont. writestartarray ();
Foreach (datarow itemrow in dt. rows)
{
Jsont. writestartobject ();

Jsont. writepropertyname ("baid"); // table id
Jsont. writevalue (itemrow ["baid"]);

Jsont. writepropertyname ("PS tutorial address"); // address
Jsont. writevalue (itemrow ["psaddress"]);

Jsont. writepropertyname ("quantity"); // quantity
Jsont. writevalue (itemrow ["quantity"]);

Jsont. writepropertyname ("unit"); // unit
Jsont. writevalue (itemrow ["unit"]);

Jsont. writepropertyname ("note"); // remarks
Jsont. writevalue (itemrow ["note"]);

Jsont. writepropertyname ("contactman"); // contact
Jsont. writevalue (itemrow ["contactman"]);

Jsont. writepropertyname ("contactmobile"); // mobile phone number of the contact
Jsont. writevalue (itemrow ["contactmobile"]);

Jsont. writepropertyname ("bid"); // Project id
Jsont. writevalue (itemrow ["bid"]);

Jsont. writepropertyname ("productid"); // product id
Jsont. writevalue (itemrow ["productid"]);
Jsont. writeendobject ();
}
Jsont. writeendarray ();
}
}
Else
{
Context. response. output. write ("[]");
}
}
}


Instance Code 2

/// When the page is loaded
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void page_load (object sender, eventargs e)
{
// Determine whether the request is asynchronous
If (request. querystring ["ajax"] = "1 ")
{
Processrequest ();
}
}
/// <Summary>
/// Process asynchronous requests
/// </Summary>
Private void processrequest ()
{
Response. contenttype = "text/html ";
String json = request. form ["json"];
// Deserialize the able
Datatable newdtb = json2dtb (json );
// Serialize the datatable to json
String back = dtb2json (newdtb );
Response. write (back );
Response. end ();
}
/// <Summary>
/// Convert datatable to json
/// </Summary>
/// <Param name = "dtb"> </param>
/// <Returns> </returns>
Private string dtb2json (datatable dtb)
{
Webpage special effect serializer jss = new javascriptserializer ();
Arraylist dic = new arraylist ();
Foreach (datarow row in dtb. rows)
{
Dictionary <string, object> drow = new dictionary <string, object> ();
Foreach (datacolumn col in dtb. columns)
{
Drow. add (col. columnname, row [col. columnname]);
}
Dic. add (drow );
}
Return jss. serialize (dic );
}
/// <Summary>
/// Convert json to datatable
/// </Summary>
/// <Param name = "json"> </param>
/// <Returns> </returns>
Private datatable json2dtb (string json)
{
Javascriptserializer jss = new javascriptserializer ();
Arraylist dic = jss. deserialize <arraylist> (json );
Datatable dtb = new datatable ();
If (dic. count> 0)
{
Foreach (dictionary <string, object> drow in dic)
{
If (dtb. columns. count = 0)
{
Foreach (string key in drow. keys)
{
Dtb. columns. add (key, drow [key]. gettype ());
}
}
Datarow row = dtb. newrow ();
Foreach (string key in drow. keys)
{
Row [key] = drow [key];
}
Dtb. rows. add (row );
}
}
Return dtb;
}

Jquery code

 

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
<Script type = "text/javascript" src = "js/jquery-1.4.2.min.js"> </script>
<Script type = "text/javascript" src = "js/json2.js"> </script>
<Script type = "text/javascript">
// Onload
$ (Function (){
// Click botton1
$ ("# Botton1"). click (function (){
Var url = "default. aspx? Ajax = 1 ";
Var dtb = generatedtb ();
// Serialize the object
Var postdata = json. stringify (dtb );
// Asynchronous request
$. Post (url, {json: postdata}, function (json ){
Createtable (json );
}, "Json ")
});
});
// Generate a able object
Function generatedtb (){
Var dtb = new array ();
For (var I = 0; I <10; I ++ ){
Var row = new object ();
Row. col1 = I;
Row. col2 = I % 2 = 0? True: false;
Row. col3 = I + "henll" ow ";
Dtb. push (row );
}
Return dtb;
}
// Display data in json
Function createtable (json ){
Var table = $ ("<table border = '1'> </table> ");
For (var I = 0; I <json. length; I ++ ){
O1 = json [I];
Var row = $ ("<tr> </tr> ");
For (key in o1 ){
Var td = $ ("<td> </td> ");
Td. text (o1 [key]. tostring ());
Td. appendto (row );
}
Row. appendto (table );
}
Table. appendto ($ ("# back "));
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Input id = "botton1" type = "button" value = "button"/>
<Div id = "back">
</Div>
</Div>
</Form>
</Body>
</Html>

If the datatable and json types can be easily converted to each other, they can be solved.
Advantages: 1) Avoid unnecessary backhaul;
2) Streamline the size of asynchronous request data;
3) Solve the Problem of tedious data sending and receiving when the data volume is large.

 

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.