[英]jQuery AJAX post data is null in c# web api controller
I am sending data to a c# web api controller
by using the following call. 我使用以下调用将数据发送到
c# web api controller
。
$.ajax({
type: "POST",
url: "menuApi/menu/Cost",
data: JSON.stringify(order),
contentType: "application/json",
success: function (data) { window.alert('done')},
dataType: 'json'
});
The c# controller
on server side is like this: 服务器端的
c# controller
是这样的:
public string Cost([FromBody] string order)
{
var sOrder = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(order);
return "";
}
The order object in Javascript is a complex object with nested arrays and properties. Javascript中的订单对象是具有嵌套数组和属性的复杂对象。 I am getting data as null.
我将数据作为null。 I am not sure how can I get the order sent through the ajax call.
我不知道如何通过ajax调用发送订单。
Edit: This is my order object 编辑:这是我的订单对象
var order = {
name:"",
id:"",
cost:"",
details: {
sItem:[{name:"",cost:""}],
dItem:[{name:"",cost:"", components:[{name:"",quantity:""}]}]
}
}
Got it, you need to post the ajax request as form data with empty parameter/form field name like this: 知道了,你需要将ajax请求作为带有空参数/表单字段名称的表单数据发布,如下所示:
var order = {
name: "",
id: "",
cost: "",
details: {
sItem: [{ name: "", cost: "" }],
dItem: [{ name: "", cost: "", components: [{ name: "", quantity: "" }] }]
}
};
$.ajax({
type: "POST",
url: "api/Values",
data: {'': JSON.stringify(order)} ,
success: function (data) { window.alert('done') },
});
The model binder's already done it for you, no need for deserializing. 模型绑定器已经为您完成,无需反序列化。 You just need to change parameter type to
object
or dynamic
. 您只需将参数类型更改为
object
或dynamic
。 Thing left is consideration to remove that redundant processing: 左边是考虑删除冗余处理:
public string Cost([FromBody] object order)
{
var sOrder = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(order.ToString());
return "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.