ASP.NET MVC 绑定到字典 [英] ASP.NET MVC Binding to a dictionary

查看:34
本文介绍了ASP.NET MVC 绑定到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to bind dictionary values within MVC.

在我的行动中:

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

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

在我的视图中:

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

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

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

推荐答案

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

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

参数的索引必须是连续的,从0开始,没有任何间隙.目前的助手不支持这个,所以你应该自己创建表单输入字段.

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.

你当然可以实现你自己的活页夹,像这样:http://siphon9.net/loune/2009/12/a-intuitive-dictionary-model-binder-for-asp-net-mvc/

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/

这篇关于ASP.NET MVC 绑定到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆