模型绑定字典

我的控制器操作方法将Dictionary传递给视图。 我认为我有以下几点:

     

下面是我处理POST操作的action方法:

 [HttpPost] public virtual ActionResult MyMethod(Dictionary items) { // do stuff........ return View(); } 

当我在文本框中输入一些值并点击提交按钮时,POST操作方法没有得到任何项目? 我究竟做错了什么?

我建议你阅读这篇博文 ,了解你的输入字段应该如何命名,以便你可以绑定到字典。 因此,您需要为密钥添加一个额外的隐藏字段:

     

可以通过以下方式生成:

 <% var index = 0; %> <% foreach (var key in Model.Keys) { %> <%: Html.Hidden("items[" + index + "].Key", key) %> <%: Html.TextBox("items[" + index +"].Value", Model[key]) %> <% index++; %> <% } %> 

这就是说,我个人建议你不要在你的观点中使用词典。 它们很丑陋,为了为模型绑定器生成专有名称,您需要编写丑陋的代码。 我会使用视图模型。 这是一个例子:

模型:

 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 items) { return View(items); } } 

查看( ~/Views/Home/Index.aspx ):

 <% using (Html.BeginForm()) { %> <%: Html.EditorForModel() %>  <% } %> 

编辑模板( ~/Views/Home/EditorTemplates/MyViewModel.ascx ):

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <%: Html.HiddenFor(x => x.Key) %> <%: Html.TextBoxFor(x => x.Value) %>