In my model, I have a person defined as
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; } = false;
public virtual List<Person>? Children { get; set }
}
and a ModelView that looks like this
public class ParentChild
{
public Person Person { get; set; }
public List<Person> PeopleToChooseFrom { get; set; }
public string searchString { get; set; }
}
In the view, I build a table like this
<table>
<thead>
<input type="hidden" asp-for="@Model.Person.Id" />
....
</thead>
<tbody>
for (int i=0; i < Model.PeopleToChooseFrom.Count; i++)
{
<tr>
<td>
<input asp-for="@Model.PeopleToChooseFrom[i].IsSelected" type="checkbox" value="" />
</td>
<td>
<input asp-for="@Model.PeopleToChooseFrom[i].Name" readonly/>
</td>
<td>
<input asp-for="@Model.PeopleToChooseFrom[i].Id" type=hidden" .>
...
}
</tbody>
When I return to the controller, everything is right except the IsSelected
field. What am I missing?
In ASP.NET Core MVC, the value of a checkbox is not automatically bound to model properties when the form is submitted. In your case, the IsSelected field is not getting updated because the form doesn't know how to map the checkbox state back to your Person model's IsSelected property.
To correct this, you can explicitly set the value attribute of the checkbox to true, and add a hidden input field with the same name but the value false. This way, when the checkbox is checked, the value true will be sent; otherwise, the value false will be sent.
Here's how to update your checkbox HTML:
<td>
<input type="hidden" asp-for="@Model.PeopleToChooseFrom[i].IsSelected" value="false" />
<input asp-for="@Model.PeopleToChooseFrom[i].IsSelected" type="checkbox" value="true" />
</td>
This ensures that IsSelected is either true or false based on whether the checkbox is checked or not.