jQuery submits post json data to webApi
- 2021-07-12 04:41:43
- OfStack
When the page thinks about webApi post json data, it is found that webapi can not directly accept data in the way of json (note: I didn't find a good way to come to post json data); But it can be transmitted in the form of data structure;
As follows:
//js Code
var d = {
Id: "1",
Name: "name",
Value: "OldValue", 7 };
$.ajax({
type: "post",
url: url1,
data: JSON.stringify({
pConfig: d
}),
success:function(d){
}
});
public class Diff
{
public string Id { set; get; }
public string Name { set; get; }
public string Value { set; get; }
}
public Diff post([FromBody]Diff pConfig)
{
List<DiffConfig> s = pConfig;
return s;
}
There is no problem with code like this; The data of a standard structure is obtained.
But if you change to the following code, you will find that there is no data
//js Code
var d = [{
Id: "1",
Name: "name",
Value: "Value",
},{
Id: "2",
Name: "name2",
Value: "Value2",
}];
$.ajax({
type: "post",
url: url1,
data: JSON.stringify({
pConfig: d
}),
success:function(d){
}
});
public List<Diff> post([FromBody]List<Diff> diff)
{
List<Diff> d = diff;
return d;
}
Such code will find that the data has not been transmitted, and it will be discovered later that there is a problem with the ajax transmission data type of the original jq; The default value of the transmitted data type contentType is "application/x-www-form-urlencoded". The default value is suitable for most cases. However, it can't adapt to the value of this transmission. If contentType: 'application/json' is set to 1, ok can be achieved; There is no problem in data transmission at all;
$.ajax({
type: "post",
dataType: 'json',
url: url,
contentType: 'application/json',
data: JSON.stringify(d),
success: function (d) {
}
});