jQuery的:
$('#test').click(function () {
var obj = new Object();
var childObj = new Object();
childObj.name = 'dominic';
childObj.age = 22;
obj.children = new Object ({ child : childObj });
console.log(obj);
$.ajax({
url: '@Url.Action("Test")',
type: 'POST',
data: obj,
dataType: 'json',
success: function (msg) {
//console.log(msg.status);
}
});
});
C#(MVC 4):
public JsonResult Test(testObj obj)
{
foreach (childObj child in obj.children)
{
Debug.Print(child.name);
Debug.Print(child.age);
}
return Json(null);
}
public class testObj
{
public List<childObj> children { get; set; }
}
public class childObj
{
public string name { get; set; }
public string age { get; set; }
}
当我调试时,obj
具有children
属性,但它始终为null ...在我的浏览器控制台中,它不为空...
答案 0 :(得分:10)
首先,我建议您将复杂对象从客户端发送到服务器,如JSON:
$.ajax({
url: '@Url.Action("Test")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(obj),
dataType: 'json',
success: function (msg) {
//console.log(msg.status);
}
});
需要注意的事项:
contentType: 'application/json'
data: JSON.stringify(obj)
客户端上的children
属性也必须是数组,而不是属性:
var obj = {};
var childObj = {};
childObj.name = 'dominic';
childObj.age = 22;
obj.children = [];
obj.children.push(childObj);
或简单地说:
var obj = {
children: [
{ name: 'dominic', age: 22 }
]
};
另一个评论:在服务器上,您的Age属性被定义为字符串,而在客户端上,您将其作为整数(age: 22
)传递,这是不一致的。除此之外,您不需要将所有C#属性都放在小写中。那真是太可怕了。 JavaScriptSerializer足够智能,可以遵守标准的C#命名约定:
public class TestObj
{
public List<ChildObj> Children { get; set; }
}
public class ChildObj
{
public string Name { get; set; }
public string Age { get; set; }
}