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)
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)