Eun*_* Ro 10 javascript c# ajax post asp.net-web-api
这是我的客户端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..."); }
});
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
表格Dataview URL编码
data:a
data:b
data:c
data:d
Run Code Online (Sandbox Code Playgroud)
这是我的webapi控制器方法:
public HttpResponseMessage UpdateStatusToDelete(string[] data)
Run Code Online (Sandbox Code Playgroud)
结果:
当我调试时,UpdateStatusToDelete中的data参数返回{string[0]}而不是数据:a data:b data:c data:d
我究竟做错了什么?任何帮助都非常感谢.
小智 32
对于传递简单类型,要发布的数据必须采用名称值对的形式,名称部分为空字符串.所以你需要像这样进行Ajax调用:
$.ajax({
type: "POST",
url: "/api/values",
data: { "": list },
dataType: "json",
success: function() { alert("it worked!"); },
failure: function() { alert("not working..."); }
});
Run Code Online (Sandbox Code Playgroud)
此外,在Web API操作上,使用[FromBody]属性对其进行注释.就像是:
public void Post([FromBody]string[] values)
Run Code Online (Sandbox Code Playgroud)
这应该够了吧.