How to return a datatable to the client Javascript

Source: Internet
Author: User

When a datatable is directly returned in WebService, an exception occurs in loop reference,

What is circular reference? Loop reference is on reference,

A References B, and B References A, which is a typical circular reference,

When there is a loop reference, the exception of the loop reference will be reported during JSON serialization,

For example

A datatable type is returned in WebService,

Datatable is an extremely complex object type,

This type generates a circular reference during JSON serialization,

When the system. reflection. module object is serialized, a circular reference occurs,

This will cause JSON serialization failure, resulting in the entire asynchronous WebService call failure,

Let's take a look at this failure example,

First, see. asmx

[Webmethod]
[System. Web. Script. Services. scriptmethod]
Public datatable getdatatable ()
{
Datatable mytable = new datatable ();

Datarow myrow;
Mytable. Columns. Add ("ID", typeof (string ));
Mytable. Columns. Add ("name", typeof (string ));
Mytable. Columns. Add ("sex", typeof (string ));
Mytable. Columns. Add ("fathername", typeof (string ));
Mytable. Columns. Add ("Address", typeof (string ));

String constr = webconfigurationmanager.
Connectionstrings ["Demo"]. connectionstring;
String sqlstr = "select ID card number, Student name, gender, parent name, home address from student ";

Using (sqlconnection sqlcon = new sqlconnection (constr ))
{
Sqlcon. open ();
Using (sqlcommand sqlcom = sqlcon. createcommand ())
{
Sqlcom. commandtext = sqlstr;
Using (sqldatareader sqldr = sqlcom. executereader ())
{
While (sqldr. Read ())
{
Myrow = mytable. newrow ();
Myrow ["ID"] = sqldr. getsqlstring (0). value;
Myrow ["name"] = sqldr. getsqlstring (1). value;
Myrow ["sex"] = sqldr. getboolean (2). tostring ();
Myrow ["fathername"] = sqldr. getsqlstring (3). value;
Myrow ["Address"] = sqldr. getsqlstring (4). value;
Mytable. Rows. Add (myrow );

}
}
}
}
Return mytable;
}

Obviously, the preceding WebService returns a datatable object.

Let's take a look at the client's JavaScriptCode

Function pageload (){
For more information, see _ ASP. net_ajax.demo _ 10 _ use.
Set_timeout (2000 );
For more information, see _ ASP. net_ajax.demo _ 10 _ use.
Set_defaultfailedcallback (onfailedcallback );
For more information, see _ ASP. net_ajax.demo _ 10 _ use.
Set_defaultsucceededcallback (onsucceededcallback );
}

Function getdatatable_onclick (){
In-depth introduction to _ ASP. net_ajax.demo _ 10 _ use. getdatatable ();
}

Function onfailedcallback (error, usercontext, methodname ){
VaR MSG = "";
If (methodname = "getdatatable "){
MSG + = "\ ngetdatatable: the following error occurs during asynchronous execution ";
}

MSG + = "\ n exception information:" + error. get_message ();
MSG + = "\ n exception type:" + error. get_exceptiontype ();
MSG + = "\ n Status Code:" + error. get_statuscode ();
MSG + = "\ n stack information:" + error. get_stacktrace ();

Alert (MSG );
}

Function onsucceededcallback (result, usercontext, methodname ){
}
During execution, the able will be referenced cyclically during serialization, so it is obvious that it will fail.

The result after clicking this button is

The preceding exceptions occur when datatable is directly returned from WebService,

So how can we solve this problem so that we can smoothly return data in the datatable from the server?

In fact, the following points should be clarified,

The format of data transmitted between the server and the client is JSON (JavaScript Object Notation ),

This format is simple and lightweight,

The most commonly used string type,List <t> set type and

Dictionary dictionary <string, T> type for data transmission and conversion,

The special example is dictionary <string, T>,

The first type must be string. Otherwise, it cannot be recognized by the client,

The datatable or dataset complex data types are far beyond the range of the preceding three types,

Therefore, normal JSON serialization cannot be performed,

So how can we pass the data in the datatable to JavaScript normally?

There are two ways to solve this problem,

The first is to use javascriptconverter for implementation,

The second is the custom data type,

The datatable complex data types are first converted to the above three data types before being passed.

This article mainly explains the second method,

The first method is more complex. You must define your converter to implement it,

At the same time, register the converter in Web. config,

In addition, it is relatively cumbersome to manually remove or set circular references,

However, the second method is relatively simple,

Because I first convert a able to a custom data type on the server,

Then, I returned my custom data type, which indirectly realized the returned datatable,

The first type uses javascriptconverter to directly return the able.

Improvement: (this allows the previous failure example to successfully return data in the datatable)

You can add a class to convert a able to list <t> or dictionary <string, T> to return data,

The class code is as follows:

Public class demo _ 10 _ use _ Converter
{
Private datatable mytable;

// Input a datatable In the constructor
Public demo _ 10 _ use _ converter (datatable mytable)
{
This. mytable = mytable;
}

// Pay attention to the returned type. After datatable is converted, the returned type is list <t>
// Multi-Level list is defined here
// The first level list stores each row in the datatable, that is, the second level list
// The second list is used to store data in each row of the datatable, that is, Dictionary
// While dictionary is used to store the values of each cell
Public list <dictionary <string, string> converter ()
{
// Level 1 List
List <list <dictionary <string, string> firstlist =
New List <list <dictionary <string, string> ();
// Traverse each row of the datatable
For (INT I = 0; I <this. mytable. Rows. Count; I ++)
{
// List Level 2
List <dictionary <string, string> secondlist =
New List <dictionary <string, string> ();
// Traverse each column of the datatable
For (Int J = 0; j <this. mytable. Columns. Count; j ++)
{
// Obtain the column name of the column where the cell is located
String columnname = This. mytable. Columns [J]. columnname;
Dictionary <string, string> mydictionary =
New Dictionary <string, string> ();
// Store the value of this cell in the dictionary
Mydictionary [columnname] = This. mytable. Rows [I] [J]. tostring ();
Secondlist. Add (mydictionary );
}
Firstlist. Add (secondlist );
}
Return firstlist;
}
}

Then you can change the WebService to a little bit.

The next step is to parse in Javascript,

Passed list <dictionary <string, string> type and Output

Let's look at the results.

This part of the code needs to be carefully considered and understood.

The above is an example of passing a able to the client JavaScript on the server side,

You can study it slowly.

2010-1-27

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.