jQuery 如何在asp.net 中使用JSON 和JQuery 从WebMethod 返回DataTable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20324737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:07:00  来源:igfitidea点击:

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

jqueryasp.netjsonasynchronousdatatable

提问by SHEKHAR SHETE

I am new to JSON. I have created a sample which returns the Stringfrom WebMethodand assign the value returned to asp.net Labelcontrol.

我是新手JSON。我创建了一个示例,它返回StringfromWebMethod并将返回的值分配给asp.net Label控件。

Sample JSON returning String:

JSON 返回字符串示例:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<script type="text/javascript" src="http://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):

在 .cs 文件中(返回字符串):

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

This works fine.

这工作正常。

How to access DataTableusing JSONand JQuery?

如何访问DataTableusingJSONJQuery

[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 DataTableusing JSON & JQuery. Please suggest me the right method to ReturnDataTableusing JSON.

我想返回 DataTable 并绑定 GridView/AccessDataTable使用 JSON & JQuery 的每一行。请建议我正确的ReturnDataTable使用方法JSON

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

我已经看到一些使用示例handlers和一些使用示例WebMethod。使用哪一种?

What are the Benefits one over the other.

一个比另一个有什么好处。

Help Appreciated!

帮助赞赏!

回答by Abide Masaraure

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

这是我通常的做法。我将DataTable内容加载到字典中,将其序列化,一切正常。您可以修改代码以满足您的需要。

[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.

在你的 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 GridViewsee link here

有很多关于如何使用 JavaScript 或 jquery 加载网格视图的教程。这至少会给你一个起点。你可以在这里找到一个很好的例子。要使用这里的GridView链接进行 CRUD 操作