我希望在GET请求中通过URI发送一个包含嵌套数组的复杂对象到MVC操作方法中。
请考虑以下代码:
public ActionResult AutoCompleteHandler([FromUri]PartsQuery partsQuery){ ... }
public class PartsQuery
{
public Part[] Parts {get; set; }
public string LastKey { get; set; }
public string Term { get; set; }
}
$.ajax({
url: "Controller/AutoCompleteHandler",
data: $.param({
Parts: [{ hasLabel: "label", hasType: "type", hasIndex : 1 }],
LastKey : "Last Key",
Term : "Term"
}),
dataType: "json",
success: function(jsonData) { ... }
});
这在使用MVC Web Api中的默认模型绑定器时可以正常工作并正确地进行绑定。
但是,如果将其切换为普通的MVC而不是WebApi,则默认的模型绑定器会崩溃,并且无法绑定嵌套数组中对象的属性:
观察列表
partsQuery != null //Good
--LastKey == "Last Key" //Good
--Term == "Term" //Good
--Parts[] != null //Good
----hasLabel == null //Failed to bind
----hasType == null //Failed to bind
----hasIndex == 0 //Failed to bind
我想知道为什么这在普通MVC中会出现问题,以及如何使
FromUriAttribute
在普通MVC中正确绑定该对象。
Part[] Parts
更改为ICollection<Part> Parts
会发生什么?你能展示一下Part
类的定义吗? - Erik PhilipsPart
是否有无参数的构造函数? - Erik PhilipsGet
方法? - Erik PhilipsFromUriAttribute
起作用的根本问题,否则我将在我的评论中使用正则表达式。 - parliament