.NET Convert DataTable to JSON

facebooktwittergoogle_plusredditpinterestlinkedinmail

Here is a neat little method I found on the ASP.NET forums for converting a DataTable into JSON objects for use by web services : written by Chandra Prakash Andani. Its a little older now but its still good stuff.


public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List> rows = new List>();
Dictionary row = null;

foreach (DataRow dr in dt.Rows) {
row = new Dictionary();
foreach (DataColumn col in dt.Columns) {
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}

The original article is located here:
http://forums.asp.net/t/1572961.aspx/1

7 thoughts on “.NET Convert DataTable to JSON

  1. binding kendo grid with run time columns from data table

    This doesnt even need a serializer. This is my function.

    public JsonResult GetManagerDaysBeyondCPD(string assignedDept, DateTime? startDateTime, DateTime? endDateTime)
    {
    DataView Data = new DataView();

    DataTable managerDaysBeyondCPDList = odrRepo.GetReportData(“Days Beyond CPD”, assignedDept, startDateTime, endDateTime);

    List<Dictionary> rows = new List<Dictionary>();
    Dictionary row = null;

    foreach (DataRow dr in managerDaysBeyondCPDList.Rows)
    {
    row = new Dictionary();

    foreach (DataColumn col in managerDaysBeyondCPDList.Columns)
    {
    string colName = col.ColumnName.Replace(” “, “_”);
    row.Add(colName, dr[col]);
    }
    rows.Add(row);
    }

    return Json(new { Data = rows }, JsonRequestBehavior.AllowGet);

    }

    And on html view, I’m using kendo grid, so it is json call and creating kendo grid runtime. You may have to customize on how you get data to ur grid

    this is in my .html page

    $(document).ready(function () {
    GLA.SummaryReports.DaysSinceLastUpdate.GetDaysSinceLastUpdateGridData(); //to display data first time when tab is created,a call to this fn will be only once from here

    });

    and in javascript code:
    GLA.SummaryReports.DaysSinceLastUpdate = function () {

    var _viewAction = “/GLA6/NSSOperationsDashboard/NSSOperationsDashboard.Web/SummaryReportsType/DaysSinceLastUpdate”;
    var gridSelector = “#grid_DaysSinceLastUpdate”;
    var tabName = “Days Since Last Update”;

    return {
    LoadDaysSinceLastUpdate: function () {
    GLA.SummaryReports.DaysSinceLastUpdate.GetDaysSinceLastUpdateGridData();

    },

    GetDaysSinceLastUpdateGridData: function () {

    var dept = $(“#cmbAssignedTo”).data(“kendoDropDownList”).dataItem().value;
    var smryStartDateTime = $(“#smryStartDateTime”).data(“kendoDatePicker”);
    var smryEndDateTime = $(“#smryEndDateTime”).data(“kendoDatePicker”);
    var smrystartDate = smryStartDateTime.value() == null ? null : new Date(smryStartDateTime.value()).toDateString();
    var smryendDate = smryEndDateTime.value() == null ? null : new Date(smryEndDateTime.value()).toDateString();

    $.get(“/GLA6/NSSOperationsDashboard/NSSOperationsDashboard.Web/SummaryReportsType/GetDaysSinceLastUpdate”, { assignedDept: dept, startDateTime: smrystartDate, endDateTime: smryendDate },

    function (e) {
    GLA.SummaryReports.CreateKendoGrid(e.Data, gridSelector, tabName);
    } GLA.Utilities.GridUtil.setData(gridSelector, e.Data);//u will need to customize this in ur code

    });
    }
    }//return
    } ();

    and finally
    CreateKendoGrid: function (args, gridSelector, tabName) {

    var obj = {};
    obj.columns = [];
    $.each(args[0], function (i, n) {
    obj.columns.push({ title: colName, field: i, width: 150 });
    }
    });

    obj.height = gheight;
    obj.groupable = true;
    obj.sortable = true;

    $(gridSelector).removeData().empty();//need to clear the grid everytime before we bind new data else unexpected error

    $(gridSelector).kendoGrid(obj);
    var datagrid = $(gridSelector).data(“kendoGrid”);

    }

    you can parse this in javascript by making the return data as Json result. u will need to install different dlls for that.If my code helped you, please leave a comment back

  2. actually this is the dayssincelastupdate.chtml

    $(document).ready(function () {
    GLA.SummaryReports.DaysSinceLastUpdate.GetDaysSinceLastUpdateGridData(); //to display data first time when tab is created,a call to this fn will be only once from here
    // $(“#grid_DaysSinceLastUpdate th”).css(‘text-align’, ‘center’);

    });

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>