I have a simple project that I want to send information via form and multiple check boxes in asp.net mvc.
This is the view:
And this is the controller method:
[HttpPost]
public ActionResult Index(Customer customer)
{
if (customer != null)
{
return Content(customer.Name.ToString());
}
return Content("empty");
}
I know that I am getting a single variable in the controller method but the point is that if I put an IEnumerable
type like list, array or even IEnumerable
itself I will receive null value, and if I put a single variable the view page only sends the value of the first checkbox.
Here you can see that I have chosen the B option but the view still returns the A option.
CodePudding user response:
Model binding to a list doesn't play nicely with foreach
; you need to use for
instead.
Which means you'll need to change your model to be an indexable list.
@model IReadOnlyList<WebApplication2.Models.Customer>
...
@for (int index = 0; index < Model.Count; index )
{
<tr>
<td>@Html.DisplayFor(m => m[index].Name)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { Model[index].ID })
@Html.ActionLink("Details", "Details", new { Model[index].ID })
@Html.ActionLink("Delete", "Delete", new { Model[index].ID })
@Html.CheckBoxFor(m => m[index].IsSelected)
@Html.HiddenFor(m => m[index].ID)
@Html.HiddenFor(m => m.[index].Name)
</td>
</tr>
}