将json对象发布到ASP MVC无法正常工作

我正在尝试将自定义Json对象发布到ASP.NET MVC控制器,但无法正常工作。

我的JS代码是:

var myData = { "Message": "Another message", "Value": 4, "FirstItem": { "ItemName": "Este es el primer Item" }, "SecondItem": { "ItemName": "Este es el segundo Item" } }; $('.clickeable').click(function () { $.ajax({ type: 'POST', dataType: 'json', data: myData, url: '@Url.Action("PostSomething")', success: function () { console.info('Success'); }, error: function () { console.info('Error'); } }); }); 

在我的控制器中:

 [HttpPost] public JsonResult PostSomething(SimpleModel model) { return Json(true); } public class SimpleModel { public string Message { get; set; } public int Value { get; set; } public SimpleItem FirstItem { get; set; } public SimpleItem SecondItem { get; set; } } public class SimpleItem { public string ItemName { get; set; } //more depth, } 

获取HttpPost时,属性FirstItem和SecondItem始终为null。 发布JsonObject

提前致谢。

 I have tried your scenario.I found out solution that var myData = { "Message": "Another message", "Value": 4, "FirstItem": { "ItemName": "Este es el primer Item" }, "SecondItem": { "ItemName": "Este es el segundo Item" } }; var obj = { 'model': myData }; var val=JSON.stringify(obj); $('.clickeable').click(function () { $.ajax({ type: 'POST', dataType: 'json', data: val, contentType:"application/json", url: '@Url.Action("PostSomething")', success: function () { console.info('Success'); }, error: function () { console.info('Error'); } }); }); 

在你的代码中你没有指定内容类型。只是试试这个

不是一个合适的解决方案但尝试

 [HttpPost] public JsonResult PostSomething(string Message, int Value,SimpleItem FirstItem,SimpleItem SecondItem ) { return Json(true); } 

这是因为jQuery如何将你的JSON对象转换为POST参数会让C#读取它的能力混乱(jQuery尝试将javascript对象的属性映射到post上的变量,MVC足够聪明,只是让原始的JSON发布了它) 。

最简单的解决方案是首先对其进行字符串化,然后应该正确地进行反序列化( data: JSON.stringify(myData) )。

请注意,如果您支持旧浏览器,则需要为该function添加json2.js库,但它内置于所有现代浏览器中。