Home >Backend Development >C++ >Why is my MVC form failing to post a list of objects?
In an MVC application, a form containing a list of objects does not submit the list to the controller correctly. After submitting the form, the list of objects received by the controller is empty.
The problem stems from the missing index of the list item in the form element. The model binder requires indexes to distinguish elements in the list.
To solve this problem, use templates instead of partial views.
1. Create editor template
In the "EditorTemplates" folder under the view folder, create an editor template named "PlanCompareViewModel.cshtml". Place the following code into your template:
<code>@model PlanCompareViewModel <div> @Html.HiddenFor(p => p.PlanID) @Html.HiddenFor(p => p.CurrentPlan) @Html.CheckBoxFor(p => p.ShouldCompare) </div></code>
2. Modify the parent view
Update the parent view as follows:
<code>@model IEnumerable<plancompareviewmodel> @using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" })) { <div> @Html.EditorForModel() </div> }</code>
DisplayTemplates and EditorTemplates automatically handle indexing for collections, ensuring the model binder creates the correct list of objects.
The above is the detailed content of Why is my MVC form failing to post a list of objects?. For more information, please follow other related articles on the PHP Chinese website!