【问题标题】:cannot call webmethod with parameters无法调用带参数的 web 方法
【发布时间】:2020-09-19 08:40:40
【问题描述】:

我在 C# 中有一个 web 方法,当它没有参数时,我调用到达 web 方法中的断点。

    [WebMethod]
    public static string GetIDForDownloadExcel()
    {
        ChartEdit cd = new ChartEdit();
        Guid clientID = Guid.NewGuid();
        return JsonConvert.SerializeObject(new { ClientID = clientID, filename = "ExportToExcel" });
    }

我使用以下代码调用它。

         function GetReportID() {                
            $.ajax({
                type: "POST",
                url: '<%= ResolveUrl("ChartEdit.aspx/GetIDForDownloadExcel") %>',
                data: JSON.stringify({ ind: indicatorsIds, loc: locationsIds }),
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    alert('Data: ' + data.d);
                },
                error: function (xhr, status, error) {
                    alert(xhr.responseText);
                }
            });

你可以看到,webmethod 没有参数。在方法中可以达到断点。然后我想让webmethod接收ajax传入的json数据(data: JSON.stringify({ ind: indicatorIds, loc:locationIds }),我把WebMethod改成如下有参数的。

    [WebMethod]
    public static string GetIDForDownloadExcel(string ind,string loc)
    {
        ChartEdit cd = new ChartEdit();
        Guid clientID = Guid.NewGuid();

        return JsonConvert.SerializeObject(new { ClientID = clientID, filename = "ExportToExcel" });
    }

但是,webmethod 无法再次到达,它无法到达方法中的断点。怎么调用可以接收json传入的数据的webmethod?

【问题讨论】:

  • 如果你删除JSON.stringify(会发生什么?
  • 还有 - contentType: "application/json; charset=utf-8",
  • var data = { "ind": indicatorIds, "loc": locationsIds };在使用 data: JSON.stringify(data) 的 ajax 中,它可能会对您有所帮助。你能在请求中写什么json发送到服务器吗?
  • 是不是意味着在HetIDForDownloadExcel中添加参数是没有问题的,可以调用成功?
  • 我对代码没有任何问题。我复制的唯一方法是发送未定义的数据:JSON.stringify({ ind: undefined , loc: undefined })。你确定 indicatorIds 和 locationsIds 有值吗?

标签: c# webmethod


【解决方案1】:

我在 ajax 中打印错误响应文本。如下:

type 'system.string' is not supported for deserialization of an array 

所以我发现是C#中webmethod的签名参数的问题,因为 ajax 传入数组变量。但是c#中的参数是

(string ind,string loc)

我改成数组变量(stirng[] ind, string[] loc),然后就可以调用webmethod了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多