我有一个AJAX请求,它使用POST请求从MVC视图向控制器发送JSON对象:
function sendData(subscriptionJson) {
$.ajax({
type: "POST",
url: '@Url.Action("SubscribeSecurities", "Subscription")',
data: '{"subscriptions": ' + subscriptionJson + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("success response: " + response.responseText);
alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
console.log("failure response: " + response.responseText);
alert(response.responseText);
},
error: function (response) {
console.log("error response: " + response.responseText);
alert(response.responseText);
}
});
}
控制器操作具有以下定义:
[HttpPost]
public ActionResult SubscribeSecurities(string subscriptions)
{
JSON具有以下格式:
{
"Subscriptions": {
"Obj1": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj2": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj3": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
}
}
}
可能导致此问题的原因是什么?
以下是我创建对象以存储JSON POST请求返回的值后所做的更新。
JSON
var test = {
"Obj1": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj2": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
},
"Obj3": {
"Value1": "3454234",
"Value2": "345643564",
"Value3": "665445",
"Value4": "True"
}
}
抓住JSON的模型
public class RootObject {
// Give this a better name. RootObject is a horrible name.
public IEnumerable<SubscriptionObj> Subscriptions { get; set; }
}
public class SubscriptionObj
{
public Int64 Value1 {get;set;}
public Int64 Value2 {get;set;}
public Int64 Value3 {get;set;}
public Boolean Value4 {get;set;}
}
答案 0 :(得分:2)
您的控制器需要string
,但您要向其发送自定义对象。
将json更改为字符串,或将控制器所期望的内容更改为与发送内容匹配的对象...例如:
public class RootObject {
// Give this a better name. RootObject is a horrible name.
public Subscriptions Subscriptions {get;set;} = new Subscriptions();
}
public class Subscriptions {
public Subscription Obj1 {get;set;} = new Subscription();
public Subscription Obj2 {get;set;} = new Subscription();
public Subscription Obj3 {get;set;} = new Subscription();
}
public class Subscription {
public Int64 Value1 {get;set;}=0;
public Int64 Value2 {get;set;}=0;
public Int64 Value3 {get;set;}=0;
public Boolean Value4 {get;set;}=false;
}
您的MVC控制器会自动将传入的json字符串反序列化为真实对象。如果反序列化的对象不是字符串,则它不会将传入的json传递给Action的字符串参数。