MVC model not binding to dictionary

前端 未结 1 841
执念已碎
执念已碎 2021-01-06 18:03

I am using ASP.Net MVC4 (Razor). I have the following code:

Dictionary occasionList = new Dictionary

相关标签:
1条回答
  • 2021-01-06 18:37

    The model binder treats the dictionary as a collection, if you imagine the dictionary as an IEnumerable<KeyValuePair<string, IEnumerable<OccasionObject>>> it is easy to understand why it isn't bound.

    What @Html.CheckBoxFor(m=>m.occasionList[s].FirstOrDefault(ev=>ev.ID == o.ID).isAttending); is generating is:

    <input type="checkbox" name="occasionList[0].Value.isAttending" ../>

    so the Key is missing.

    Try this:

    @Html.Hidden("occasionList.Index", s)
    @Html.CheckBoxFor(m=>m.occasionList[s].FirstOrDefault(ev=>ev.ID == o.ID).isAttending);
    @Html.HiddenFor(m=>m.occasionList[s].Key)
    

    The first hidden is because you potentially will have your indexes out of order, and explicitly providing an ".Index" is the only way to have the model binder work under those circumstances.

    Here's another resource that describes model binding to collections.

    0 讨论(0)
提交回复
热议问题