ASP.NET MVC绑定到字典

use*_*344 64 c# asp.net-mvc dictionary model-binding

我正在尝试绑定MVC中的字典值.

在我的行动中:

model.Params = new Dictionary<string, string>();

model.Params.Add("Value1", "1");
model.Params.Add("Value2", "2");
model.Params.Add("Value3", "3");
Run Code Online (Sandbox Code Playgroud)

在视图中我有:

@foreach (KeyValuePair<string, string> kvp in Model.Params)
{ 
<tr>
  <td>
    <input type="hidden" name="Params.Key" value="@kvp.Key" />
    @Html.TextBox("Params[" + kvp.Key + "]")
  </td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)

但是视图不显示初始值,并且在提交表单时Params属性为null?

Ant*_*t P 85

In ASP.NET MVC 4, the default model binder will bind dictionaries using the typical dictionary indexer syntax property[key].

If you have a Dictionary<string, string> in your model, you can now bind back to it directly with the following markup:

<input type="hidden" name="MyDictionary[MyKey]" value="MyValue" />
Run Code Online (Sandbox Code Playgroud)

For example, if you want to use a set of checkboxes to select a subset of a dictionary's elements and bind back to the same property, you can do the following:

@foreach(var kvp in Model.MyDictionary)
{
    <input type="checkbox" name="@("MyDictionary[" + kvp.Key + "]")"
        value="@kvp.Value" />
}
Run Code Online (Sandbox Code Playgroud)

  • 似乎不适用于数字键,但使用字符串. (9认同)
  • 有人可以提供任何更详细的答案链接吗?尝试使用Dictionary <int,bool>并且它没有用,所以我不得不使用旧的索引器语法. (5认同)

Jok*_*kin 57

你应该看一下scott hanselman的这篇文章:http: //www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

默认活页夹只是以以下格式理解字典:

params[0].key = kvp.key
params[0].value = kvp.value
Run Code Online (Sandbox Code Playgroud)

参数的索引必须是连续的,从0开始并且没有任何间隙.当前的帮助程序不支持此功能,因此您应该自己创建表单输入字段.

你当然可以实现自己的绑定器,如下所示:http: //siphon9.net/loune/2009/12/a-intuitive-dictionary-model-binder-for-asp-net-mvc/


Sph*_*xxx 22

在@ AntP的答案的基础上,有一个更简洁的方式,让MVC做更多的工作(至少TextBoxFor()Dictionary<string, string>- 我没有尝试CheckBoxFor()Dictionary<xxx, bool>):

@foreach(var kvp in Model.MyDictionary)
{
    @Html.Label(kvp.Key);
    @Html.TextBoxFor(m => m.MyDictionary[kvp.Key]);
}
Run Code Online (Sandbox Code Playgroud)

  • 我只是使用 `Dictionary&lt;Enum, string&gt;` 尝试了这个,但没有用。如果我改用`Dictionary&lt;string, string&gt;`,它会起作用。有人对此有解释吗? (2认同)
  • 我的经验是,值可以是任何东西,但键必须是“string”而不是“int”。也许模型绑定器将其与位置参数混淆了。 (2认同)