【问题标题】:Is POSTing a Dictionary to an .NET MVC action possible?是否可以将字典发布到 .NET MVC 操作?
【发布时间】:2011-02-09 22:11:11
【问题描述】:

我有一个包含一系列字段的表单,例如:

<input type="text" name="User[123]" value="Alice" />
<input type="text" name="User[456]" value="Bob" />
...

其中用户数组的索引(123 和 456)是与值关联的 ID。我正在尝试在控制器中更新这些值。 我的想法是,将 ID 映射到名称的字典会起作用,但会创建如下操作:

public void Save(Dictionary<string, string> user) {
    // ...
}

导致用户参数为空。

那么,传递字典可能吗?或者,还有其他方法可以实现吗?

【问题讨论】:

    标签: .net asp.net asp.net-mvc


    【解决方案1】:

    列表可以使用,我相信它也可以用于字典。通读 Phil Haack 的 Model Binding to a List,了解列表绑定的工作原理。

    你应该可以这样做:

    <input type="hidden" name="User.Index" value="123" />
    <input type="text" name="User[123]" value="Alice" />
    
    <input type="hidden" name="User.Index" value="456" />
    <input type="text" name="User[456]" value="Bob" />
    

    【讨论】:

    • 那个帖子已经过时了。绑定到列表的格式已更改,您无需指定索引。
    • 帖子没有过时。它更新了与 MVC 2 相关的信息,并考虑到“.index”是可选的。
    • @Levi 你确定吗?上面的代码示例对我不起作用。我在 Save 方法中将 null 作为用户参数。我有 MVC 2 RTM 和 VS 2008。
    • 请记住 - 当您将模型绑定到字典时,您实际上是在绑定到 ICollection>。所以你需要 User[x].Key 和 User[x].Value (重构 KeyValuePair 对象)。有关示例,请参见 marcomagdy.com/2009/09/03/…
    【解决方案2】:

    请参阅http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx 了解绑定到字典所需的语法。请特别注意在该帖子的一半左右绑定 MSFT + AAPL 公司代码的示例。

    【讨论】:

      【解决方案3】:

      对于 ASP.NET MVC 2 使用这个:

      <input type="hidden" name="User[0].Key" value="123" />
      <input type="text" name="User[0].Value" value="Alice" />
      
      <input type="hidden" name="User[1].Key" value="456" />
      <input type="text" name="User[1].Value" value="Bob" />
      

      您需要一个额外的隐藏字段 User[i].Key。 i 是从零开始的索引。它应该是不间断的。

      当您模型绑定到字典时,您实际上是绑定到ICollection&lt;KeyValuePair&lt;,&gt;&gt;。所以你需要 User[x].Key 和 User[x].Value (重构 KeyValuePair 对象)

      参考文献

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      相关资源
      最近更新 更多