Click here to Skip to main content
6,611,284 members and growing! (20,945 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Convert ASP.NET DataTable to JSON, to use datatable in JAVASCRIPT

By blue_arc

This Class will help developers, to convert their data table into ready to use JSON string on client end Javascript
Javascript, HTML, C# 1.0, C# 2.0, Windows, .NET CF, Mobile, .NET 1.0, .NET 1.1, .NET 2.0, ASP.NET, ADO.NET, WebForms, VS.NET2003, Dev
Posted:29 Jun 2007
Views:29,023
Bookmarked:27 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
3 votes for this article.
Popularity: 1.27 Rating: 2.67 out of 5
1 vote, 33.3%
1

2
1 vote, 33.3%
3
1 vote, 33.3%
4

5

Introduction

Web development is changing day by day, and it has been changing from the day one. Now days every developer has his/her own writing style. Some like pure, server side, so some like mixture. Now days Javascript is just like a boom in the market. And the way MS (Microsoft) has implemented it, is a great job.

But there are still many things we do on our own. So here I am going to demonstrate a example by which we can convert ASP.net Data Table in to JSON string in two ways. So it will be very useful to use it in Javascript.

This will solve the problem for developers that how to use Server data on client in well structured manner.

Backgorund

It is assumed that the person who will use this, is containning a good knowledge of JSON. how to maipulate it in the server.

Code

public string JSON_DataTable(DataTable dt)

        {


            /****************************************************************************

             * Without goingin to the depth of the functioning of this Method, i will try to give an overview

             * As soon as this method gets a DataTable it starts to convert it into JSON String,


 

             * it takes each row and ineach row it creates an array of cells and in each cell is having its data

             * on the client side it is very usefull for direct binding of object to  TABLE.


             * Values Can be Access on clien in this way. OBJ.TABLE[0].ROW[0].CELL[0].DATA 

             * NOTE: One negative point. by this method user will not be able to call any cell by its name.

             * *************************************************************************/


 

            StringBuilder JsonString = new StringBuilder();

 

            JsonString.Append("{ ");

            JsonString.Append("\"TABLE\":[{ ");


            JsonString.Append("\"ROW\":[ ");


 

            for (int i = 0; i < dt.Rows.Count; i++)

            {


 

 

                JsonString.Append("{ ");

                JsonString.Append("\"COL\":[ ");

                for (int j = 0; j < dt.Columns.Count; j++)

                {

                    if (j < dt.Columns.Count - 1)

                    {

                        JsonString.Append("{" + "\"DATA\":\"" + dt.Rows[i][j].ToString() + "\"},");

                    }

                    else if (j == dt.Columns.Count - 1)

                    {

                        JsonString.Append("{" + "\"DATA\":\"" + dt.Rows[i][j].ToString() + "\"}");

                    }

                }




                /*end Of String*/




                if (i == dt.Rows.Count - 1)

                {

                    JsonString.Append("]} ");

                }

                else

                {

                    JsonString.Append("]}, ");

                }

            }

            JsonString.Append("]}]}");

            return JsonString.ToString();

        }



b)


public string CreateJsonParameters(DataTable dt)

        {

            /* /****************************************************************************

             * Without goingin to the depth of the functioning of this Method, i will try to give an overview

             * As soon as this method gets a DataTable it starts to convert it into JSON String,

             * it takes each row and in each row it grabs the cell name and its data.

             * This kind of JSON is very usefull when developer have to have Column name of the .

             * Values Can be Access on clien in this way. OBJ.HEAD[0].<ColumnName>

             * NOTE: One negative point. by this method user will not be able to call any cell by its index.

             * *************************************************************************/

            StringBuilder JsonString = new StringBuilder();

            //Exception Handling        


            if (dt != null && dt.Rows.Count > 0)

            {

                JsonString.Append("{ ");

                JsonString.Append("\"Head\":[ ");

                for (int i = 0; i < dt.Rows.Count; i++)

                {

                    JsonString.Append("{ ");

                    for (int j = 0; j < dt.Columns.Count; j++)


                    {

                        if (j < dt.Columns.Count - 1)

                        {

                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");

                        }

                        else if (j == dt.Columns.Count - 1)

                        {

                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");

                        }

                    }

                    /*end Of String*/

                    if (i == dt.Rows.Count - 1)

                    {

                        JsonString.Append("} ");

                    }

                    else

                    {

                        JsonString.Append("}, ");

                    }

                }

                JsonString.Append("]}");

                return JsonString.ToString();

            }

            else

            {



                return null;

            }

        }



 

USING THE CODE

As you can see that the code is very easy to understand. These functions are ready to use. You can find full source code in the download source code section.

Using the code

Using The JSON_DataTable method

Steps:

1) //Add namespace

using Ravs.Factory.JSON;

2) //Create Object

JSON_Class Object_JSON_Class = new JSON_Class();

3) Use of First Case JSON

Object_JSON_Class. JSON_DataTable(ProvideRequiredDataTable);

// Here the above method will provide a JSON Stirng which you can use on the client.

4) Now put this data in someplace where it is very easy to render to the client for further uses.. I'll Show how to put it in to a text field(the most easy one.)

Put a server text box on to your form. And do this.

ServerSideTextBox.Text= Object_JSON_Class. JSON_DataTable(ProvideRequiredDataTable);

5) On Client End.. Use javascript like this.

<script type='text/javascript'>

var oServerSideTextBox= document.getElementbyId("ServerSideTextBox");

var oServerJSON_String=eval("("+oServerSideTextBox .value+")");

alert(oServerJSON.TABLE[0].ROW[0].COL[0].DATA);

// if alert comes with right Data then, CHEERS J

</script>

Using The CreateJsonParameters method

Steps:

6) //Add namespace

using Ravs.Factory.JSON;

7) //Create Object

JSON_Class Object_JSON_Class = new JSON_Class();

8) Use of First Case JSON

Object_JSON_Class. CreateJsonParameters (ProvideRequiredDataTable);

// Here the above method will provide a JSON Stirng which you can use on the client.

9) Now put this data in someplace where it is very easy to render to the client for further uses.. I'll Show how to put it in to a text field(the most easy one.)

Put a server text box on to your form. And do this.

ServerSideTextBox.Text= Object_JSON_Class.CreateJsonParameters (ProvideRequiredDataTable);

10) On Client End.. Use javascript like this.

<script type='text/javascript'>

var oServerSideTextBox= document.getElementbyId("ServerSideTextBox");

var oServerJSON_String=eval("("+oServerSideTextBox .value+")");

alert(oServerJSON.HEAD[0].AnyColumnName);

// if alert comes with right Data then, CHEERS J

</script>

NOTE: To Know Understand check out the Source and demo projects.

Cheers :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

blue_arc


Member
My Name is Ravi Kant Srivastava. Alias= ravs

I am an Indian lives in India.
I am a graduate in Economics, and a computer student from childhood. Professionally i am working as a Sr. Software Engg(mumbai).
In IT i am working from more than 4 years.
I personally like work on javascript and AJAX, Asp.net 2.0/3.5, WCF, WF, WPF, Silverlight - c#.
My hobbies are- palying cricket(i love it man).
good music, eating, solving complex algo's.

Occupation: Software Developer (Senior)
Company: Connexxions Business Support Services
Location: India India

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralSuggestions [modified] PinmemberAlexandru Matei10:19 11 Sep '07  
AnswerRe: Suggestions Pinmemberblue_arc22:02 11 Sep '07  
GeneralRe: Suggestions PinmemberAndrew Timmins11:25 5 Nov '07  
GeneralAppendFormat PinsupporterMark Nischalke3:09 29 Jun '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Jun 2007
Editor:
Copyright 2007 by blue_arc
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project