0

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:

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.

choosing B option

getting A option

1 Answer 1

1

Model binding to a list doesn't play nicely with foreach; you need to use for instead.

ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries - Scott Hanselman's Blog

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>
}
1
  • thank you mate. i have looked for that goddmn bug for 2 weeks. you solved that. thank u very much Feb 4, 2022 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.