如何从 C# WebMethod 获取数据作为 Dictionary<> 并使用 jquery ajax 显示响应?

How to get data from C# WebMethod as Dictionary<> and display response using jquery ajax?

这里是return类型我要returnDictionary<ReportID, ReportDatail> 其中 类 的结构为:

Class ReportDetail
{
    ReportID,
    ReportName,
    ReportShortName,
    List<ReportFields>
}

Class ReportFields
{
    SystemName,
    DBName,
    DataType,
    MaxLength,
    DefaultValue
}

我不知道如何return将该响应作为字典。

function GetReportsDetails(AccoutType) {
    $.ajax({
    type: "POST",
    url: '<%= ResolveUrl("~/Web/ReportPosition.aspx/GetReportDetail") %>',
        contentType: "application/json; charset=utf-8",
        datatype: 'json',
        data: JSON.stringify({SelectedAccount: AccoutType}),
        success: function (data) {
        alert(data.d);
        },
        error: function (xhr, status, error) {
            alert('XHR: ' + xhr.responseText + '\nStatus: ' + status + '\nError: ' + error);
        }
});

[WebMethod]
public static string GetReportDetail(string AccoutItem)
{
    return "Response from WebMethod..!";
    //What type of code I've to write here to return "Dictionary<ReportID, ReportDatail>" 

}

在上面的 web 方法中,我只使用 return 字符串而不是字典作为响应,但仍然会出现错误: Type \u0027System.String\u0027 is not supported for deserialization of an array.

如何将数据传递给 WebMethod 并将响应 return 作为来自 WebMethod

的字典进行处理

试试这个:

定义要发送的 class 类型:

public class DataAccountItem
{
    public string SelectedAccount { get; set; }
}

[WebMethod] 中,您需要像这样传递 class:

    [WebMethod]
public static string GetReportDetail(DataAccountItem myItem)
{
    return "Response from WebMethod..!";
    //What type of code I've to write here to return "Dictionary<ReportID, ReportDatail>" 

}

Type "System.String" is not supported for deserialization of an array.

我不清楚为什么这段代码给出了这条错误信息。但是无论如何,您都可以简化其中的一些序列化。由于该方法只需要一个字符串,因此只给它一个以预期参数名称作为键的字符串。我假设 JavaScript 代码中的 AccountType 是一个字符串:

data: { AccountItem: AccountType }

I don't know how to return Dictionary<> respose

与您 return 任何事情的方式相同。所以,例如,如果你想 return a Dictionary<int, ReportDetail> 你可以这样做:

[WebMethod]
public static Dictionary<int, ReportDetail> GetReportDetail(string AccoutItem)
{
    return new Dictionary<int, ReportDetail>();
}

至于如何使用 实际数据 填充 该对象(而不仅仅是 return 一个空字典) , 这完全取决于你。

and process using jquery over that

当您 return 实际数据时,使用浏览器的调试工具检查 JSON 响应的结构。它实际上只是一个对象数组。您可以遍历它,检查对象的属性等,就像任何其他对象一样。

success: function (data) {
    for (var i = 0; i < data.length; i++) {
        // do something with data[i]
    }
}