Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 28 Jun 2007
Rate this:
Please Sign up or sign in to vote.
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

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. using Ravs.Factory.JSON;
  3. Create the object:
  4. JSON_Class Object_JSON_Class = new JSON_Class();
  5. Use of first case JSON:
  6. 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:

    ServerSideTextBox.Text= Object_JSON_Class. JSON_DataTable(ProvideRequiredDataTable);
  9. On the client end.. use JavaScript like this:
  10. <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. using Ravs.Factory.JSON; 
  3. Create the object:
  4. JSON_Class Object_JSON_Class = new JSON_Class(); 
  5. Use of first case JSON:
  6. 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.

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

License

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

Share

About the Author

blue_arc
Architect
India India
My Name is Ravi Kant Srivastava. Alias= ravs
 
DOTNET Consultant
Mumbai
Group type: Social Group (No members)



Comments and Discussions

 
GeneralMy vote of 4 PinmemberJeffrey Schaefer25-Nov-11 21:50 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140921.1 | Last Updated 29 Jun 2007
Article Copyright 2007 by blue_arc
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid