且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC绑定到字典

更新时间:2022-10-15 07:47:00

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



默认的绑定器只是以格式了解字典:

  params [0] .key = kvp.key 
params [0] .value = kvp.value

参数的索引必须是顺序的,从0开始,没有任何间隙。目前的帮助者不支持这一点,所以您应该自己创建表单输入字段。



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


I'm trying to bind dictionary values within MVC.

Within the action I have:

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

model.Params.Add("Value1", "1");
model.Params.Add("Value2", "2");
model.Params.Add("Value3", "3");

and within the view I have:

@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>
}

But the view doesn't display the initial values, and when the form is submitted the Params property is null?

you should take a look to this post from scott hanselman: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

The default binder just understand dictionaries in the format:

params[0].key = kvp.key
params[0].value = kvp.value

The index of the param must be sequential, starting from 0 and without any gaps. The current helpers don't support this, so you should create the form input fields by yourself.

you can of course implement your own binder, like this one: http://siphon9.net/loune/2009/12/a-intuitive-dictionary-model-binder-for-asp-net-mvc/