Thursday, August 16, 2012

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 http://bresleveloper.blogspot.co.il/2012/04/ajax-3-simle-ways.html
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:

[WebMethod]
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)
   {
      l.Add(
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');
            newTable.appendChild(tbody);

            var r = d[0];
            for (var p in r) {
               var th = document.createElement('th');
               th.innerText = p;
               tbody.appendChild(th);
            }
            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];
                  tr.appendChild(td);
               }
               tbody.appendChild(tr);
            }
            $(
"#wrapper").html(newTable);
            $(newTable).addClass("GridStyle");
            newTable.setAttribute("border", "1");
         }
      };
   $.ajax(options);
});


2 comments: