Your first problem is that you are using the foreach , creating duplicate name attributes that will not bind to the collection, and as a result, the BillLists parameter BillLists always be an empty collection (duplicate id attributes that are invalid html will also generate it). You need to use a for loop or a custom EditorTemplate for typeof BillCheck . Using a for loop, your view should be
using (Html.BeginForm("MakeDue", "Home")) { @Html.ValidationSummary(true) @for(int i = 0; i < Model.DueList.Count; i++) { <tr> <td> @Html.HiddenFor(m => m.DueList[i].id) @Html.DisplayFor(m => m.DueList[i].flat)</td> <td>@Html.DisplayFor(m => m.DueList[i].name)</td> <td>@Html.TextBoxFor(m => m.DueList[i].due)</td> </tr> } <input type="submit" class="btn btn-success" value="Update" /> }
Note that the @Html.HiddenFor() must be inside the <td> element in order to be a valid html.
The next problem is that the model in the view is not a List<BillCheck> , but it does contain a property called DueList , which is typeof List<BillCheck> , so your POST method should be
public ActionResult MakeDue(YourModel model)
where YourModel is the name of the class that you used to create the view (i.e. in the @model ??? instruction). Then you should use a loop in the controller method
foreach (var BillId in model.DueList) { var getDue = db.BillChecks.Where(p => p.id == BillId.id).FirstOrDefault(); if (getDue != null)
Note the addition of an if (getDue != null) check if (getDue != null)
Side note: you are checking if (ModelState.IsValid) . It is recommended that the ModelState view be ModelState invalid so that the user can fix any errors.
source share