Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c# - how to post json object array to a web api

How can I post a JSON array to a Web API? It's working for single object.

This is what I've tried, but the controller seems to be returning 0 rather than the expected 3.

This is my 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 call:

$.ajax({
           url: urlString,
           type: 'POST',
           data: sc,
           dataType: 'json',
           crossDomain: true,
           cache: false,
           success: function (data) { console.log(data); }
        });

Web API controller:

[HttpPost]
public string PostProducts([FromBody]List<SyncingControl> persons)
{
    return persons.Count.ToString(); // 0, expected 3
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is an error in the json Table_ID": "Allergy_Trns" should be "Table_ID": "Allergy_Trns".

Missing double quote.

Update

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); }
    });

Notice the JSON.stringify(sc), @herbi is partly correct too about specifying a content type.

Screen grab

**Screen grab**


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...