如何将json对象数组发布到Web API [英] how to post json object array to a web api
问题描述
如何将JSON数组发布到Web API?它适用于单个对象.
How can I post a JSON array to a Web API? It's working for single object.
这是我尝试过的方法,但是控制器似乎返回了0
而不是预期的3
.
This is what I've tried, but the controller seems to be returning 0
rather than the expected 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"
}];
AJAX呼叫:
$.ajax({
url: urlString,
type: 'POST',
data: sc,
dataType: 'json',
crossDomain: true,
cache: false,
success: function (data) { console.log(data); }
});
Web API控制器:
Web API controller:
[HttpPost]
public string PostProducts([FromBody]List<SyncingControl> persons)
{
return persons.Count.ToString(); // 0, expected 3
}
推荐答案
json中的错误Table_ID": "Allergy_Trns"
应该为"Table_ID": "Allergy_Trns"
.
There is an error in the json Table_ID": "Allergy_Trns"
should be "Table_ID": "Allergy_Trns"
.
缺少双引号.
更新
您需要确保将参数作为json发送,如下所示:
You need to make sure that you are sending your parameters as json as follows:
$.ajax({
url: urlString,
type: 'POST',
data: JSON.stringify(sc),
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
cache: false,
success: function (data) { console.log(data); }
});
请注意JSON.stringify(sc)
,@ herbi在指定内容类型方面也部分正确.
Notice the JSON.stringify(sc)
, @herbi is partly correct too about specifying a content type.
屏幕抓取
这篇关于如何将json对象数组发布到Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!