我有以下javascript代码段:
$.ajax({
url: self.LoadCirculationListUrl,
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: [ { "ColumnName":"France","Comparitor":"=","Value":"1"},{"ColumnName":"Germany","Comparitor":">","Value":"3"}]
});
以下是从上面的ajax调用中访问的controllre:
public ActionResult LoadCirculationData(IList<CirculationListFilter> filters)
{
}
这是CirculationListFilter
类
public sealed class CirculationListFilter
{
public string ColumnName { get; set; }
public string Comparitor { get; set; }
public string Value { get; set; }
}
现在,当我运行代码时,控制器没有传递给它的JSON集合; filters
始终为空。但是,如果我这样做:
$.ajax({
url: self.LoadCirculationListUrl,
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { "ColumnName":"Germany","Comparitor":">","Value":"3"}
});
并且控制器是这样的:
public ActionResult LoadCirculationData(CirculationListFilter filters)
{
}
数据传递正常。为什么控制器无法绑定JSON项的集合?
编辑:
我更改了AJAX调用以使用它:
data: { filters: [{ "ColumnName": "France", "Comparitor": "=", "Value": "1" }, { "ColumnName": "Germany", "Comparitor": ">", "Value": "3" }]},
和ActionResult:
public ActionResult LoadCirculationData(List<CirculationListFilter> filters)
现在filters
里面有2个项目,但每个CirculationListFilter
类都在其属性中填充了NULL数据。所以我越来越近了,但实际值没有被绑定。
答案 0 :(得分:4)
问题出在.ajax()调用中。
.ajax()不会将数据转换为JSON字符串。
它适用于一个项目的原因是因为.ajax()能够将数据转换为MVC愉快接受的查询字符串。
解决方案是首先将JSON转换为字符串:
$.ajax({
url: self.LoadCirculationListUrl,
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify([ { "ColumnName":"France","Comparitor":"=","Value":"1"},{"ColumnName":"Germany","Comparitor":">","Value":"3"}])
});
答案 1 :(得分:0)
我找到了另一个解决方案:
Ajax电话:
data: { 'json': '[{ "ColumnName": "France", "Comparitor": "=", "Value": "1" }, { "ColumnName": "Germany", "Comparitor": ">", "Value": "3" }]' },
控制器:
public ActionResult LoadCirculationData(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
var obj = js.Deserialize<List<CirculationListFilter>>(json);
}
上面给出了我需要的物品。真的不确定为什么JSON绑定器默认不这样做。
答案 2 :(得分:0)
如果您想以这种格式接收
public ActionResult LoadCirculationData(IList<CirculationListFilter> filters)
{
}
您需要将其发布到下一格式数据中:{
{
"ColumnName[0]":"Germany","Comparitor[0]":">","Value[0]":"3",
"ColumnName[1]":"Germany","Comparitor[1]":">","Value[1]":"3",
"ColumnName[2]":"Germany","Comparitor[2]":">","Value[2]":"3",
"ColumnName[3]":"Germany","Comparitor[3]":">","Value[3]":"3",
"ColumnName[4]":"Germany","Comparitor[4]":">","Value[4]":"3",
}