How to implement a view in MVC to display the Dictionary in the model and map the dictionary back to the model

Let's say you have this model:

//model public class Stuff { public string Name { get; set; } public Dictionary<String, String> Description { get; set; } } 

I want to be able to create an action and an appropriate view so that users can add an Object Name object to the form and add several descriptive entries.

In this particular case, I want the key to be a language code of the type "en", "de", "fr", "es", etc., and the description should be the corresponding description for this language.

For example, in the view, you can see something like this:

 @model Stuff @using(Html.BeginForm()) { <div> @Html.LabelFor(x=>x.Name) @Html.TextBoxFor(x=>x.Name) </div> <div> <!-- What goes in here to map to the Dictionary in the Stuff Model? --> <input name="LanguageCode" value="en" /> <input name="DescriptionValue" /> <input name="LanguageCode" value="de" /> <input name="DescriptionValue" /> <input name="LanguageCode" value="fr" /> <input name="DescriptionValue" /> </div> <div> <input type="submit" value="save" /> </div> } // controller [HttpGet] public ActionResult Index () { return View(new Stuff()); } [HttpPost] public ActionResult Index (Stuff myStuff) { foreach(KeyValuePair kvp in myStuff.Description) { Trace.WriteLine(String.Format("Language: {0} - Description: {1}", kvp.Key, kvp.Value)); } DBHelper.Save(myStuff); return View(); } 

Any alternative decisions are made.

Thanks.

+7
source share
2 answers

It will be something like this:

 @int i = 0; @foreach (var item in Model.Description) { <input name="Description[@i].Key" value="@item.Key" /> <input name="Description[@i].Value" value="@item.Value" /> @i++ } 

See this post by Scott Hanselman

+13
source

You can create an editor template (and display template) for your dictionary type. Then MVC will be able to display dictionary instances in your models.

For example, in your model, you can specify a template to use as follows:

 public class Stuff { public string Name { get; set; } [UIHint("Stringdictionary")] public Dictionary<String, String> Description { get; set; } } 

in your view, you should do just that:

 @model Stuff @using(Html.BeginForm()) { <div> @Html.LabelFor(x=>x.Name) @Html.TextBoxFor(x=>x.Name) </div> <div> @Html.Editor(x=>x.Description ) </div> <div> <input type="submit" value="save" /> </div> } 

And the editor template (you should create it in the Views / Shared / EditorTemplates folder) could be something like this:

 @model Dictionary<string,string> @foreach (var item in Model) { @Html.EditorFor(x=>x.Key) @Html.EditorFor(x=>x.Value) } 
+5
source

All Articles