Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a checkbox list in ASP.NET Core?

I am looking to implement a checkboxlist in ASP.NET Core, but am facing some difficulties.

My ViewModel:

public class GroupIndexViewModel {     public Filter[] Filters { get; set; } }  public class Filter {     public int Id { get; set; }     public string Name { get; set; }     public bool Selected { get; set; } } 

My View:

@model GroupIndexViewModel <form asp-action="Index" asp-controller="Group" method="get">   <ul>   @for (var i = 0; i < Model.Filters.Length; i++)   {     <li>       <input type="checkbox" id="@Model.Filters[i].Name" asp-for="@Model.Filters[i].Selected" value="@Model.Filters[i].Selected" checked="@Model.Filters[i].Selected" />       <label for="@Model.Filters[i].Name">@Model.Filters[i].Name</label>     </li>   }   </ul>   <button type="submit" name="action">Filtrer</button> </form> 

When posting to my controller, the Filter property in my viewmodel shows selected false even though it is selected in the view.

like image 388
Arnstein Avatar asked Nov 11 '16 20:11

Arnstein


People also ask

What is checkbox list in asp net?

ASP.NET CheckBoxList is a web control that can be used to collate the items that can be checked, thus giving the user the ability to select multiple items simultaneously. This list of items in the CheckBoxList can be dynamically generated using the Data Binding functions.

How do I use a checkbox in a razor page?

Razor offers two ways to generate checkboxes. The recommended approach is to use the input tag helper. Any boolean property of the PageModel will render a checkbox if it is passed to the asp-for attribute, so long as the property is not nullable: public class IndexModel : PageModel.


1 Answers

I would do following way.

@model GroupIndexViewModel <form asp-action="Index" asp-controller="Group" method="get">     <ul>         @for (var i = 0; i < Model.Filters.Count; i++)         {             <li>                        <input type="checkbox" asp-for="@Model.Filters[i].Selected"  />                 <label asp-for="@Model.Filters[i].Selected">@Model.Filters[i].Name</label>                 <input type="hidden" asp-for="@Model.Filters[i].Id" />                 <input type="hidden" asp-for="@Model.Filters[i].Name" />                             </li>         }     </ul>     <button type="submit" name="action">Filtrer</button> </form> 

Here I assuming that you have proper implementation of controller and action.

like image 186
dotnetstep Avatar answered Oct 01 '22 04:10

dotnetstep