How to bind a dictionary type parameter for both GET and POST actions for ASP.NET MVC

I want to define a view that displays a list of labels and a check box, the user can change this check box and then send back. I have a problem sending a dictionary. That is, the dictionary parameter for the post method is null.

The following are the steps for the GET and POST actions:

public ActionResult MasterEdit(int id) { Dictionary<string, bool> kv = new Dictionary<string, bool>() { {"A", true}, {"B", false} }; return View(kv); } [HttpPost] public ActionResult MasterEdit(Dictionary<string, bool> kv) { return RedirectToAction("MasterEdit", new { id = 1 }); } 

Beliw is a performance

 @model System.Collections.Generic.Dictionary<string, bool> @{ ViewBag.Title = "Edit"; } <h2> MasterEdit</h2> @using (Html.BeginForm()) { <table> @foreach(var dic in Model) { <tr> @dic.Key <input type="checkbox" name="kv" value="@dic.Value" /> </tr> } </table> <input type="submit" value="Save" /> } 

Any idea would be greatly appreciated!

+3
source share
2 answers

Do not use the dictionary for this. They do not fit very well with model binding. Maybe PITA.

A view model would be more appropriate:

 public class MyViewModel { public string Id { get; set; } public bool Checked { get; set; } } 

then the controller:

 public class HomeController : Controller { public ActionResult Index() { var model = new[] { new MyViewModel { Id = "A", Checked = true }, new MyViewModel { Id = "B", Checked = false }, }; return View(model); } [HttpPost] public ActionResult Index(IEnumerable<MyViewModel> model) { return View(model); } } 

then the corresponding view ( ~/Views/Home/Index.cshtml ):

 @model IEnumerable<MyViewModel> @using (Html.BeginForm()) { <table> <thead> <tr> <th></th> </tr> </thead> <tbody> @Html.EditorForModel() </tbody> </table> <input type="submit" value="Save" /> } 

and finally, the corresponding editor template ( ~/Views/Home/EditorTemplates/MyViewModel.cshtml ):

 @model MyViewModel <tr> <td> @Html.HiddenFor(x => x.Id) @Html.CheckBoxFor(x => x.Checked) @Html.DisplayFor(x => x.Id) </td> </tr> 
+5
source

Take a look at this article from scott hanselman. There are examples of model binding to a dictionary, lists, etc.

+2
source

Source: https://habr.com/ru/post/1484533/


All Articles