I have form which is made up of a List model. When the form is submitted back to action method, the list is null. How can I set this up?
public ActionResult PendingRenewals()
{
//get list elements
var customers = get customer that match our criteria;
//Build list
List<string[]> renewals = new List<string[]>();
foreach(var item in customers)
{
renewals.Add(new string[] {item.name, item.id, item.PO });
}
return View(renewals);
}
View
@model List<string[]>
@using (Html.BeginForm()
{
<input type="submit" value="Save"/>
<table>
@foreach (var item in Model)
{
<tr>
<td>item[0]</td>
<td>item[1]</td>
<td>@Html.EditorFor(model => item[2])</td>
</td>
</tr>
}
</table>
}
Back to Controller
[HttpPost]
public ActionResult PendingRenewals(List<string[]> renewal, string EntityId)
{
//renewals is always null
return PendingRenewals();
}
Solution
Using FortyTwo’s idea, I used a string[][] as the model, so the view looks like this (model[i][0]) and model[i][1] are the fields that I need passed back to the controller):
@model string[][]
@for (int i = 0; i < Model.Length; i++ )
{
<tr>
<td>@Model[i][2]</td>
<td>@Model[i][3]</td>
<td>@Model[i][4]</td>
<td>@Model[i][5]</td>
<td>@Html.HiddenFor(model => model[i][0]) @Html.TextBoxFor(model => Model[i][1])</td>
</tr>
}
You need to use an old fashioned for loop. This way, the indexer is used to respect the naming conventions needed by mvc’s model binder.