Ran*_*ngh 16 c# asp.net jquery json asp.net-web-api
如何将JSON数组发布到Web API?它适用于单个对象.
这是我试过的,但控制器似乎正在返回0而不是预期3.
这是我的JSON:
var sc = [{
"ID": "5",
"Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a",
"Table_ID": "Allergy_Trns",
"Checksum": "-475090533",
"LastModified": "2015-01-22T20:08:52.013"
},
{
"ID": "5",
"Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a",
"Table_ID": "Allergy_Trns",
"Checksum": "-475090533",
"LastModified": "2015-01-22T20:08:52.013"
},
{
"ID": "5",
"Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a",
"Table_ID": "Allergy_Trns",
"Checksum": "-475090533",
"LastModified": "2015-01-22T20:08:52.013"
}];
Run Code Online (Sandbox Code Playgroud)
AJAX电话:
$.ajax({
url: urlString,
type: 'POST',
data: sc,
dataType: 'json',
crossDomain: true,
cache: false,
success: function (data) { console.log(data); }
});
Run Code Online (Sandbox Code Playgroud)
Web API控制器:
[HttpPost]
public string PostProducts([FromBody]List<SyncingControl> persons)
{
return persons.Count.ToString(); // 0, expected 3
}
Run Code Online (Sandbox Code Playgroud)
hut*_*oid 17
Table_ID": "Allergy_Trns"应该是json中有错误"Table_ID": "Allergy_Trns".
缺少双引号.
更新
您需要确保将参数发送为json,如下所示:
$.ajax({
url: urlString,
type: 'POST',
data: JSON.stringify(sc),
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
cache: false,
success: function (data) { console.log(data); }
});
Run Code Online (Sandbox Code Playgroud)
注意JSON.stringify(sc),@herbi在指定内容类型方面也是部分正确的.
屏幕抓取
