c# - 使用 [FromUri] 属性 - 将复杂对象与嵌套数组绑定(bind)

标签 c# asp.net-mvc model-binding

我想将在 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/

相关文章:

c# - jquery 窗口值在 ASP.NET 代码后面无法访问

c# - 将 Generic<Derived> 转换为 Generic<Base>

c# - C# 或 Java 有 lambda 的原因是什么?

javascript - 使用 jquery 将 textarea 中的文本添加到表中

asp.net-mvc - 如何在 ASP.NET Core 6 MVC 应用程序中动态添加 Controller

c# - asp.net mvc jquery $.post 列表<字符串>

entity-framework - 我如何 ModelBind 与 MVC 3 和 Entity Framework Code First 的多对多关系?

c# - 从 WinRT 下的 WebView 复制内容

c# - 使用默认行为将模型绑定(bind)到接口(interface)

c# - 如何检查自定义模型 Binder 中的属性属性