Passing DataTable with Ajax from C# to JavaScript

answer is - u cant!
but since ASP.NET WebMethod return Json we can do some things
about WebMethods see
the harder and smarter way is to serialize and de-serialize it but thats for next time, this post is for ANYBODY

1st thing 1st: DataRow is not serializeable so any doing with DataTable will be a mess so we create relevant class for them and into a list like that:

public static object GetDataTableJson()
   DataTable t =  MySqlDb.ExecuteSelect("QUERY");
   return GetList(t);

public static List<MyDataRow> GetList(DataTable t)
   List<MyDataRow> l = new List<MyDataRow>();
   foreach (DataRow r in t.Rows)
new MyDataRow()
          DateAndTime = r[
"Date and Time"].ToString(),
          Name = r["Name"].ToString(),
          Comments = r["Comments"].ToString()
   return l;

public class MyDataRow
   public string DateAndTime { get; set; }
   public string Name { get; set; }
   public string Comments { get; set; }

now ur Javascript (with JQ):

$(function () {
   $("#btnTest").click(function () {
      var options = {
         type: "POST",
         url: "tester.aspx/GetDataTableJson",
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
            var d = msg.d;
            var newTable = document.createElement('table');
            var tbody = document.createElement('tbody');

            var r = d[0];
            for (var p in r) {
               var th = document.createElement('th');
               th.innerText = p;
            for (var i = 0; i < d.length; i++) {
               var tr = document.createElement('tr');
               var r = d[i];
               for (var p in r) {
                  var td = document.createElement('td');
                  td.innerText = r[p];
            newTable.setAttribute("border", "1");


Post a Comment

Popular posts from this blog

c# Service Play Sound with NAudio example by Moshe

JS/JQ simulate Enter event

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem