【发布时间】:2012-03-19 14:09:12
【问题描述】:
让 ASP.NET MVC3 绑定包含列表的复杂 JSON 对象时遇到问题。
这是我的对象的结构。
public class PageModel
{
public PageModel() { }
public CustomObject1 CustomObject { get; set; }
public IEnumerable<CustomObject2> Objects { get; set; }
}
public class CustomObject1
{
public CustomObject1() { }
[Required]
public int CustomId1 { get; set; }
public string CustomName { get; set; }
}
public class CustomObject2
{
public CustomObject2() { }
[Required]
public int Custom2Id { get; set; }
public CustomObject3 SubItem { get; set; }
public int SubItemId { get; set; }
}
您可以假设CustomObject3 具有相似的结构 - 无需复制另一个组成的类,所以我认为您可以发挥您的想象力 :)
这是进行 POST 调用的 Javascript/Jquery(假设所有导致此调用的 JS 都提供了正确的数据):
//$obj1 has all data for the first object
var firstObj = { };
firstObj.CustomId1 = $obj1.Id;
firstObj.CustomName = $obj1.Name;
var i = 0;
//$objects is an array with all the data
$.each($objects, function() {
objsArray[i] = {
Custom2Id: $(this).Id,
SubItemId: $(this).itemId
};
++i;
});
$.ajax({
type: 'POST',
url: '/Action/Method',
data: { CustomObject: firstObj, Objects: objsArray },
//Success/error handlers here
});
最后(我知道,相当多的代码)这里是我所拥有的方法的概述:
public class ActionController : Controller {
public JsonResult Method(PageModel model) {
//Gets here - model.CustomObject is filled correctly, and model.Objects has a correct count of whatever data I passed to the method - but all of the properties are empty!
}
}
正如我所说,当我调试和单步执行时,第一个对象已填充,所有数据都在那里。如果我在 JSON 对象的 Objects 数组中传递两个对象,我会在控制器中看到 Count 为 2,但 Custom2Id 和 SubItemId 是空的。什么给了?
当我在$.ajax 调用中指定'application/json' 的contentType 时,MVC 抱怨正在传递的数据。也试过将MVC方法中的model参数拆分成两个单独的参数,但是没有用。
任何帮助都非常感谢 - 这个让我很难过!
【问题讨论】:
标签: jquery json asp.net-mvc-3