Pages

Tuesday, March 12, 2013

Endpoint on ASP.NET page returning JSON from DataTable

I was trying to get an web service, on my aspx page which returned data would be JSON.

The structure of JSON returned usually is something similar to this:

{ "d" :  [ {...}, {...}, {...} ] }

To achieve this, I purpose this approach:


First - Create an WebMethod on your page, at server side, like this:

        [System.Web.Services.WebMethod]
        public static string GetData()
        {
            DataTable dt = GetDataTable();
            
            return BuildJSONFromDT(dt);
        }



Second - Create the method "BuildJSONFromDT"

 

        private static string BuildJSONFromDT(DataTable dt)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            List<object> resultMain = new List<object>();

            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn column in dt.Columns)
                {
                    result.Add(column.ColumnName, "" + row[column.ColumnName]);
                }

                resultMain.Add(result);
            }

            return serializer.Serialize(resultMain);
        }



Third - At client side, do an ajax call with jquery like this:

$.ajax({
        type: "POST",
        async: true,
        contentType: "application/json; charset=utf-8",
        data: "{}",
        url: "page.aspx/GetData",
        dataType: "json",
        success: function (result) {
            var myData = eval(result.d);
            // Work on myData object (JSON)
        },
        error: function (data, textStatus, jqXHR) {
            alert("Error: " + textStatus);
        }
    });



At this point, you should have an valid JSON at client side reflecting your DataTable retrieved on server side.

Hope this helps someone.

Cheers!


Reference:
http://geekswithblogs.net/aghausman/archive/2009/05/16/datatable-to-json.aspx

No comments:

Post a Comment