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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With