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

后端 未结 1 1085
臣服心动
臣服心动 2021-01-02 16:46

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

相关标签:
1条回答
  • 2021-01-02 17:46

    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

    0 讨论(0)
提交回复
热议问题