我想将在 uri 中带有嵌套数组的复杂对象发送到 GET 请求中的 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 中的默认模型绑定(bind)器正确绑定(bind)。
但是,将其切换为普通 MVC 而不是 WebApi,默认模型绑定(bind)器就会崩溃,无法绑定(bind)嵌套数组中对象的属性:
观察列表
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 中正确绑定(bind)此对象
最佳答案
这里的核心问题是 MVC 和 WebApi 使用不同的模型绑定(bind)器。甚至基本接口(interface)也不同。
Mvc - System.Web.Mvc.IModelBinder
Web API - System.Web.Http.ModelBinding.IModelBinder
当您通过 $.ajax 调用发送数据时,您将发送以下查询字符串参数:
Parts[0][hasLabel]:label
Parts[0][hasType]:type
Parts[0][hasIndex]:1
LastKey:Last Key
Term:Term
虽然,与 MVC 默认模型绑定(bind)器绑定(bind)的正确格式对于参数名称具有不同的命名约定:
Parts[0].hasLabel:label
Parts[0].hasType:type
Parts[0].hasIndex:1
LastKey:Last Key
Term:Term
所以,这个方法调用可以工作:
$.ajax({
url: "Controller/AutoCompleteHandler?Parts[0].hasLabel=label&Parts[0].hasType=type&Parts[0].hasIndex=1&LastKey=Last+Key&Term=Term",
dataType: "json",
success: function(jsonData) { ... }
});
您需要构建符合 MVC 模型绑定(bind)器命名约定的查询字符串。
此外,示例操作中的 [FromUri]
属性完全被忽略,因为 MVC DefaultModelBinder 不知道它。
关于c# - 使用 [FromUri] 属性 - 将复杂对象与嵌套数组绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17578878/