代码之家  ›  专栏  ›  技术社区  ›  Brenton Alker

是否可以将字典发布到.net mvc操作?

  •  10
  • Brenton Alker  · 技术社区  · 15 年前

    我有一个表单,其中包含一系列字段,如:

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

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

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

    导致用户参数为空。

    那么,传字典有可能吗?或者,有没有其他方法来实现这一点?

    3 回复  |  直到 14 年前
        1
  •  12
  •   womp    15 年前

    列表是有可能的,我相信字典也有可能。通读 Model Binding to a List 作者phil haack,了解列表绑定的工作原理。

    你应该能够做到:

    <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" />
    
        2
  •  7
  •   Levi    15 年前

    http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx 用于绑定到字典所需的语法。特别要注意的是,在文章的中间部分绑定了msft+aapl公司的代码。

        3
  •  7
  •   Pavel Chuchuva grapeot    14 年前

    对于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" />
    

    您需要一个额外的隐藏字段用户[i].key。我是零基索引。应该是不间断的。

    当您将绑定到字典时,实际上是绑定到 ICollection<KeyValuePair<,>> . 因此,您需要user[x].key和user[x].value(重新构造keyvaluepair对象)

    工具书类