ASP.NET MVC dictionary binding

I am trying to bind dictionary values ​​inside MVC.

Inside 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 in 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 does not display the initial values, and when the form is submitted, is the Params property null?

+45
dictionary c # asp.net-mvc model-binding
Mar 04 '11 at 8:23
source share
3 answers

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

The default binder simply understands dictionaries in the format:

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

The parameter index must be sequential, starting at 0 and without spaces. Current helpers do not support this, so you must create the form input fields yourself.

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

+48
Apr 04 2018-11-11T00:
source share

In ASP.NET MVC 4, the middleware by default associates dictionaries using the typical syntax of the dictionary indexer property[key] .

If your model has Dictionary<string, string> , now you can bind it directly with the following markup:

 <input type="hidden" name="MyDictionary[MyKey]" value="MyValue" /> 

For example, if you want to use a set of checkboxes to select a subset of dictionary items and bind to the same property, you can do the following:

 @foreach(var kvp in Model.MyDictionary) { <input type="checkbox" name="@("MyDictionary[" + kvp.Key + "]")" value="@kvp.Value" /> } 
+73
Sep 08 '13 at 11:12
source share

Based on @AntP's answer, there is an even less detailed way that allows MVC to do most of the work (at least with TextBoxFor() on Dictionary<string, string> - I have not tried CheckBoxFor() on Dictionary<xxx, bool> ):

 @foreach(var kvp in Model.MyDictionary) { @Html.Label(kvp.Key); @Html.TextBoxFor(m => m.MyDictionary[kvp.Key]); } 
+11
Jun 01 '14 at 16:31 on
source share



All Articles