How to bind Dictionary type parameter for both GET and POST action on ASP.NET MVC

前端 未结 2 1322
梦谈多话
梦谈多话 2021-01-20 22:02

I want to define a view which displays a list of label and checkbox, user can change the checkbox, then post back. I have problem posting back the dictionary. That is, The d

相关标签:
2条回答
  • 2021-01-20 22:23

    Take a look at this post by scott hanselman. There're the examples of model binding to a dictionary, lists, etc

    0 讨论(0)
  • 2021-01-20 22:30

    Don't use a dictionary for this. They don't play well with model binding. Could be a PITA.

    A view model would be more appropriate:

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

    then a 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 a 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>
    
    0 讨论(0)
提交回复
热议问题