How to Return DataTable from WebMethod using JSON and JQuery in asp.net?

I am new to JSON. I have created a sample which returns the String from WebMethod and assign the value returned to asp.net Label control.

Sample JSON returning String:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "JSONSample.aspx/DisplayData",
            data: "{}",
            dataType: "json",
            success: function(data) {
                //alert("hi");
                $("#ctl00_MainContent_lbltxt").text(data.d);
            },
            error: function(result) {
                alert("Error");
            }
        });
    });
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

<label id="lbltxt" runat="server"></label>
</asp:Content>

In .cs file( returning String):

[WebMethod]
    public static string DisplayData()
    {
        return DateTime.Now.ToString();
    }

This works fine.

How to access DataTable using JSON and JQuery?

[WebMethod]
    public static DataTable DisplayData()
    {
        DataTable dt = new DataTable();
        return dt.GetData();
    }

I want to return the DataTable and Bind the GridView/Access each row of DataTable using JSON & JQuery. Please suggest me the right method to Return DataTable using JSON.

I have seen some sample using handlers & some sample with using WebMethod. Which one to use?

What are the Benefits one over the other.

Help Appreciated!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here is how I normally do it. I load the DataTable contents into a dictionary, serialize it and everything works. You can modify the code to suit your needs.

[WebMethod]
public string GetQueryInfo()
{
    String daresult = null;
    DataTable yourDatable = new DataTable();
    DataSet ds = new DataSet();
    ds.Tables.Add(yourDataTable);
    daresult = DataSetToJSON(ds);
    return daresult;
}

public string DataSetToJSON(DataSet ds)
{
    Dictionary < string, object > dict = new Dictionary<string, object>();
    foreach(DataTable dt in ds.Tables) {
        object[] arr = new object[dt.Rows.Count + 1];

        for (int i = 0; i <= dt.Rows.Count - 1; i++) {
            arr[i] = dt.Rows[i].ItemArray;
        }

        dict.Add(dt.TableName, arr);
    }

    JavaScriptSerializer json = new JavaScriptSerializer();
    return json.Serialize(dict);
}

On your aspx.

$.ajax({
    type: "POST",
    url: 'Webservices/GetQueryInfo',
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
        var objdata = $.parseJSON(data.d);
        // now iterate through this object's contents and load your gridview
    }
});

There are many tutorials on how to load a grid view using JavaScript or jquery. This will at least give you a starting point. You can find a nice example here.To do CRUD operations with the GridView see link here


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x