将字符串数组发送到 Web API 方法

2024-01-22

这是我的客户端 ajax 调用:

    var list = ["a", "b", "c", "d"];

    var jsonText = { data: list };

    $.ajax({
        type: "POST",
        url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
        data: jsonText,
        dataType: "json",
        traditional: true,
        success: function() { alert("it worked!"); },
        failure: function() { alert("not working..."); }
    });

这是 chrome 网络标头:

Request URL:http://localhost:2538/api/scheduledItemPriceStatus/updateStatusToDelete

Request Method:POST

Request Headersview source

Accept:application/json, text/javascript, */*; q=0.01

Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3

Accept-Encoding:gzip,deflate,sdch

Accept-Language:en-US,en;q=0.8

Connection:keep-alive

Content-Length:27

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Host:localhost:2538

Origin:http://localhost:2538

Referer:http://localhost:2538/Pricing/ScheduledItemPrices

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11

X-Requested-With:XMLHttpRequest

表单数据视图 URL 编码

data:a
data:b
data:c
data:d

这是我的 webapi 控制器方法:

public HttpResponseMessage UpdateStatusToDelete(string[] data)

result:

当我调试时,UpdateStatusToDelete中的数据参数返回{string[0]}而不是数据:a 数据:b 数据:c 数据:d

我究竟做错了什么?非常感谢任何帮助。


为了传递简单类型,要发布的数据必须采用名称值对的形式,其中名称部分为空字符串。所以你需要像这样进行 Ajax 调用:

$.ajax({
  type: "POST",
  url: "/api/values",
  data: { "": list },
  dataType: "json",
  success: function() { alert("it worked!"); },
  failure: function() { alert("not working..."); }
});

此外,在您的 Web API 操作上,使用 [FromBody] 属性对其进行注释。就像是:

public void Post([FromBody]string[] values)

这应该够了吧。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串数组发送到 Web API 方法 的相关文章

随机推荐