假设我有一个JavaScript对象:
function Parent(n, c) {
this.Name = n;
this.Children = c;
}
var p = new Parent("asdf", [1,2,3]);
我想通过JSON将parent
对象及其子对象的数组传递给MVC 4控制器。
我应该如何格式化ajax请求?我看到过一些类似于这样的问题和其他相关问题,但没有一个使用数组作为成员变量。
以下是我目前拥有的内容:
var parents = [];
parents.push(new Parent("qwer", "child1"));
parents.push(new Parent("sdfg", 12345));
parents.push(new Parent("zxcv", [4,5,6]));
$.ajax({
url: MakeUrl("Ctlr/Action"),
type: "POST",
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({
parents : parents
}),
success: function (data, state, xhr) {
$("#someDiv").html(data);
},
error: function (xhr, state, err) {
Utility.displayError(xhr.reponseText);
}
});
stringify的结果看起来很合理:
"{"parents":[{"Name":"qwer","Value":"child1"}, {"Name":"sdfg","Value":12345}, {"Name":"zxcv","Value":[4,5,6]}]}"
以下是控制器操作:
public ActionResult Action(IEnumerable<Parent> parents) {
...
}
如果相关的话,服务器端的Parent
对象是:
public class Parent {
public string Name { get; set; }
public object Children { get; set; }
}
Children
是一个 对象
,因为它有时是另一种数据类型 - 我知道这可能会有些不妥,但这个类的最终功能是将任意参数传递到我们的报告引擎中。简单数据类型似乎可以很好地以这种方式工作(日期、整数、字符串等),但
Children
数组只是出现了 {object}
,据我所知甚至不是一个字符串,而是某个通用的系统对象。在 MVC 中是否有一种方法可以做到这一点,而不需要将其推入字符串并解析它?
dynamic
而不是object
吗?这里的问题在于object
本质上不能转换为IEnumerable
。 - Mike Perrenouddynamic
会得到相同的行为。 - Hannele