Dictionary Binding Model

My controller action method passes a Dictionary<string, double?> the view. In my opinion, I have the following:

 <% foreach (var item in Model.Items) { %> <%: Html.Label(item.Key, item.Key)%> <%: Html.TextBox(item.Key, item.Value)%> <% } %> 

Below is my action method that handles the POST operation:

 [HttpPost] public virtual ActionResult MyMethod(Dictionary<string, double?> items) { // do stuff........ return View(); } 

When I enter some values ​​in a text box and press the submit button, does the POST action method return no elements? What am I doing wrong?

+6
dictionary c # asp.net-mvc-2
source share
1 answer

I would recommend that you read this blog post about how your input fields should be named so that you can attach to a dictionary. Therefore, 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 can be generated using something line by line:

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

That being said, I personally would recommend that you NOT use dictionaries in your submissions. They are ugly and in order to generate proper names for the connecting device, you need to write ugly code. I would use view models. Here is an example:

Model:

 public class MyViewModel { public string Key { get; set; } public double? Value { get; set; } } 

Controller:

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

View ( ~/Views/Home/Index.aspx ):

 <% using (Html.BeginForm()) { %> <%: Html.EditorForModel() %> <input type="submit" value="OK" /> <% } %> 

Editor Template ( ~/Views/Home/EditorTemplates/MyViewModel.ascx ):

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

All Articles