Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checkbox values not returning to controller ASP.NET Core 7 MVC

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading