Jq submits post json data to webApi, jqwebapipostjson
When thinking about webApi post json data on the page, we found that webapi cannot directly accept data in json format (Note: I didn't find a good way to post json data ); however, it can be transmitted in a data structure;
As follows:
1 // js Code
Var d = {2 Id: "1", 3 Name: "name", 4 Value: "OldValue", 7}; 8 $. ajax ({9 type: "post", 10 url: url1, 11 data: JSON. stringify ({12 pConfig: d13}), 14 success: function (d) {15 16} 17 });
1 public class Diff 2 { 3 public string Id { set; get; } 4 public string Name { set; get; } 5 public string Value { set; get; } 6 } 7 public Diff post([FromBody]Diff pConfig) 8 { 9 List<DiffConfig> s = pConfig;10 return s;11 }
View Code
There is no problem with code like this; a standard structure of data is obtained;
However, if the code below is changed, no data is found.
1 // js Code 2 var d = [{3 Id: "1", 4 Name: "name", 5 Value: "Value", 6}, {7 Id: "2", 8 Name: "name2", 9 Value: "Value2", 10}]; 11 $. ajax ({12 type: "post", 13 url: url1, 14 data: JSON. stringify ({15 pConfig: d16}), 17 success: function (d) {18 19} 20 });
View Code
1 public List<Diff> post([FromBody]List<Diff> diff)2 {3 List<Diff> d = diff;4 return d;5 }
View Code
This code will find that the data has not been passed in, and later we will find that there is a problem with the original jq ajax data transmission type; the default value of the transmitted data type contentType is "application/x-www-form-urlencoded ". The default value is applicable in most cases. But it cannot adapt to the value of this transmission. You can set contentType: 'application/json' to OK. There is no problem with data transmission;
$.ajax({ type: "post", dataType: 'json', url: url, contentType: 'application/json', data: JSON.stringify(d), success: function (d) { } });