模型绑定字典 [英] Model Binding a Dictionary
问题描述
我的控制器的操作方法传递一个词典<字符串,双>
到视图。我在我的观点如下:
My controller action method passes a Dictionary<string, double?>
to the view. I have the following in my view:
<% foreach (var item in Model.Items) { %>
<%: Html.Label(item.Key, item.Key)%>
<%: Html.TextBox(item.Key, item.Value)%>
<% } %>
下面是处理POST操作我的操作方法:
Below is my action method which handles the POST operation:
[HttpPost]
public virtual ActionResult MyMethod(Dictionary<string, double?> items)
{
// do stuff........
return View();
}
当我进入了一些值到文本框,并点击提交按钮POST操作方法没有得到任何项背?我在做什么错了?
When I enter the some values into the textbox and hit the submit button the POST action method is not getting any items back? What am I doing wrong?
推荐答案
我建议你读<一个href=\"http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx\">this博客文章你的输入域的命名方式,这样就可以绑定到一个字典。所以,你需要一个额外的隐藏字段为重点:
I would recommend you reading this blog post about how your input fields should be named so that you can bind to a dictionary. So you will need an additional hidden field for the key:
<input type="hidden" name="items[0].Key" value="key1" />
<input type="text" name="items[0].Value" value="15.4" />
<input type="hidden" name="items[1].Key" value="key2" />
<input type="text" name="items[1].Value" value="17.8" />
这可能与沿线的东西产生:
which could be generated with something along the lines:
<% var index = 0; %>
<% foreach (var key in Model.Keys) { %>
<%: Html.Hidden("items[" + index + "].Key", key) %>
<%: Html.TextBox("items[" + index +"].Value", Model[key]) %>
<% index++; %>
<% } %>
这是说,我个人会怎么不在你的看法使用字典建议。他们是丑陋的,为了生成正确的名字模型绑定,你需要写丑陋code。我会用视图模型。这里有一个例子:
This being said, personally I would recommend you NOT using dictionaries in your views. They are ugly and in order to generate proper names for the model binder you need to write ugly code. I would use view models. Here's an example:
型号:
public class MyViewModel
{
public string Key { get; set; }
public double? Value { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Key = "key1", Value = 15.4 },
new MyViewModel { Key = "key2", Value = 16.1 },
new MyViewModel { Key = "key3", Value = 20 },
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> items)
{
return View(items);
}
}
查看(〜/查看/主页/的Index.aspx
)
<% using (Html.BeginForm()) { %>
<%: Html.EditorForModel() %>
<input type="submit" value="OK" />
<% } %>
编辑模板(〜/查看/主页/ EditorTemplates / MyViewModel.ascx
)
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<Models.MyViewModel>" %>
<%: Html.HiddenFor(x => x.Key) %>
<%: Html.TextBoxFor(x => x.Value) %>
这篇关于模型绑定字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!