Click here to Skip to main content
15,879,535 members
Articles / Web Development / HTML

Convert ASP.NET DataTable to JSON, to use a DataTable in JavaScript

Rate me:
Please Sign up or sign in to vote.
4.09/5 (14 votes)
28 Jun 2007CPOL2 min read 168K   5.5K   51   11
This class will help developers to convert their data table into a ready to use JSON string on the client end JavaScript.

Introduction

Web development is changing day by day, and it has been changing from day one. Nowadays, every developer has his/her own writing style. Some like pure, server side, and some like a mixture. Nowadays 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. Here I am going to demonstrate an example by which we can convert an ASP.NET DataTable in to a JSON string in two ways. It will be very useful to use it in JavaScript.

This will solve the problem for developers on how to use server data on the client side in a well structured manner.

Background

It is assumed that the person who will use this has a good knowledge of JSON and how to manipulate it in the server.

Code

C#
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, the code is very easy to understand. These functions are ready to use. You can find the full source code in the download source code section.

Using the JSON_DataTable method

  1. Add the namespace:
  2. C#
    using Ravs.Factory.JSON;
  3. Create the object:
  4. C#
    JSON_Class Object_JSON_Class = new JSON_Class();
  5. Use of first case JSON:
  6. C#
    Object_JSON_Class.JSON_DataTable(ProvideRequiredDataTable);

    Here, the above method will provide a JSON stirng which you can use on the client.

  7. Now put this data in someplace where it is very easy to render to the client for further use. I'll show how to put it in to a text field (the most easy one.)
  8. Put a server text box on to your form. And do this:

    C#
    ServerSideTextBox.Text= Object_JSON_Class. JSON_DataTable(ProvideRequiredDataTable);
  9. On the client end.. use JavaScript like this:
  10. JavaScript
    <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

  1. Add the namespace:
  2. C#
    using Ravs.Factory.JSON; 
  3. Create the object:
  4. C#
    JSON_Class Object_JSON_Class = new JSON_Class(); 
  5. Use of first case JSON:
  6. C#
    Object_JSON_Class.CreateJsonParameters (ProvideRequiredDataTable);

    Here, the above method will provide a JSON string which you can use on the client.

  7. Now put this data in someplace where it is very easy to render to the client for further use.. I'll show how to put it in to a text field (the most easy one):
  8. Put a server text box on to your form. And do this.

    C#
    ServerSideTextBox.Text= 
      Object_JSON_Class.CreateJsonParameters (ProvideRequiredDataTable);
  9. On the client end.. use JavaScript like this:
  10. C#
    <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 more, check out the source and demo projects.

Cheers :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect V2Solutions
India India
Solution Architect, with expertise in BFSI, Mortgage, Real Estate, Education, Fleet Domain, with more than 10 years of core knowledge of .net net technologies.
This is a Social Group (No members)


Comments and Discussions

 
QuestionJson limitation and out of memory exception Pin
tolga7428-Dec-15 11:28
tolga7428-Dec-15 11:28 
QuestionI am using this with AJAX to send back JSON formatted results Pin
tjvaliant12321-Mar-12 8:22
tjvaliant12321-Mar-12 8:22 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey16-Feb-12 1:23
professionalManoj Kumar Choubey16-Feb-12 1:23 
GeneralMy vote of 4 Pin
Jeffrey Schaefer25-Nov-11 21:50
Jeffrey Schaefer25-Nov-11 21:50 
GeneralMy vote of 5 Pin
olavolsf19-Jan-11 18:31
olavolsf19-Jan-11 18:31 
GeneralMy vote of 5 Pin
fgutierrez8616-Dec-10 3:36
fgutierrez8616-Dec-10 3:36 
GeneralSuggestions [modified] Pin
Alexandru Matei11-Sep-07 9:19
Alexandru Matei11-Sep-07 9:19 
AnswerRe: Suggestions Pin
blue_arc11-Sep-07 21:02
blue_arc11-Sep-07 21:02 
GeneralRe: Suggestions Pin
Andrew Timmins5-Nov-07 10:25
Andrew Timmins5-Nov-07 10:25 
GeneralAppendFormat Pin
Not Active29-Jun-07 2:09
mentorNot Active29-Jun-07 2:09 
GeneralRe: AppendFormat Pin
KansasCoder31-Dec-09 9:20
KansasCoder31-Dec-09 9:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.