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

Standing on the shoulders of @dotnetstep and @gsxrboy73, this approach adds an optional control title and "Check All" type of checkbox. It also serializes "id" attributes so you can safely have multiple Check Box Lists on a page. This is tailored for .NET 5 binding to MVC Models in a Bootstrap environment.

I prefer thin and light models that don't rope in giant mvc libraries:

public class CheckBoxListItem
{
    public string Key { get; set; }
    public string Value { get; set; }
    public bool IsChecked { get; set; } = false;
    public bool IsDisabled { get; set; } = false;
}

A List<CheckBoxListItem> drives the Tag Helper:

/// <summary>check-box-list Tag Helper</summary>
[HtmlTargetElement("Check-Box-List", Attributes = "asp-title, asp-items, asp-model-name, asp-check-all-label", TagStructure=TagStructure.NormalOrSelfClosing)]
public class CheckBoxListTagHelper : TagHelper
{
    /// <summary>HTML element ID of the tracking form element</summary>
    [HtmlAttributeName("asp-form-id")]
    public string FormId { get; set; }

    /// <summary>Optional bolder title set above the check box list</summary>
    [HtmlAttributeName("asp-title")]
    public string ListTitle { get; set; }

    /// <summary>List of individual child/item values to be rendered as check boxes</summary>
    [HtmlAttributeName("asp-items")]
    public List<CheckBoxListItem> Items { get; set; }

    /// <summary>The name of the view model which is used for rendering html "id" and "name" attributes of each check box input.
    /// Typically the name of a List[CheckBoxListItem] property on the actual passed in @Model</summary>
    [HtmlAttributeName("asp-model-name")]
    public string ModelName { get; set; }

    /// <summary>Optional label of a "Check All" type checkbox.  If left empty, a "Check All" check box will not be rendered.</summary>
    [HtmlAttributeName("asp-check-all-label")]
    public string CheckAllLabel { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        string id = context.UniqueId;
        output.TagName = "div";
        string html = "";

        output.PreElement.AppendHtml($"<!-- Check List Box for {(string.IsNullOrEmpty(ListTitle) ? ModelName : ListTitle)} -->\r\n");

        if (!string.IsNullOrEmpty(ListTitle))
        {
            // Prepend a Title to the control
            output.PreContent.AppendHtml($"\r\n\t<label id=\"check-box-list-label-{id}\" class=\"cblTitle\">\r\n"
                + $"\t\t<strong>{ListTitle}</strong>\r\n"
                + $"\t</label>\r\n");
        }

        if (!string.IsNullOrEmpty(CheckAllLabel))
        {
            // Prepend a "Check All" type checkbox to the control
            output.PreContent.AppendHtml("\t<div class=\"form-check\">\r\n"
                + $"\t\t<input id=\"check-box-list-all-{id}\"\r\n"
                + "\t\t\tclass=\"cblCheckAllInput form-check-input\"\r\n"
                + "\t\t\ttype=\"checkbox\"\r\n"
                + $"\t\t\tvalue=\"true\"\r\n"
                );

            if (Items.All(cbli => cbli.IsChecked))
            {
                output.PreContent.AppendHtml("\t\t\tchecked=\"checked\"\r\n");
            }

            output.PreContent.AppendHtml("\t\t\t/>\r\n"
                + $"\t\t<label id=\"check-box-list-all-label-{id}\" class=\"cblCheckAllLabel form-check-label\" for=\"check-box-list-all-{id}\">\r\n"
                + $"\t\t\t&nbsp; {CheckAllLabel}\r\n"
                + "\t\t</label>\r\n"
                + "\t</div>\r\n"
                ) ;
        }

        // Begin the actual Check Box List control
        output.Content.AppendHtml($"\t<div id=\"cblContent-{id}\" class=\"cblContent\">\r\n");

        // Create an individual check box for each item
        for (int i = 0; i < Items.Count(); i++)
        {
            CheckBoxListItem item = Items[i];
            html = "\t\t<div class=\"form-check\">\r\n"
                + $"\t\t\t<input id=\"{ModelName}_{i}__IsChecked-{id}\"\r\n"
                + $"\t\t\t\tname=\"{ModelName}[{i}].IsChecked\"\r\n"
                + $"\t\t\t\tclass=\"cblCheckBox form-check-input\"\r\n"
                + $"\t\t\t\tform=\"{FormId}\"\r\n"
                + "\t\t\t\tdata-val=\"true\"\r\n"
                + "\t\t\t\ttype=\"checkbox\""
                + "\t\t\t\tvalue=\"true\""
                ;

            if (item.IsChecked)
            {
                html += "\t\t\t\tchecked=\"checked\"\r\n";
            }

            if (item.IsDisabled)
            {
                html += "\t\t\t\tdisabled=\"disabled\"\r\n";
            }

            html += "\t\t\t\t/>\r\n"
                + $"\t\t\t<label id=\"check-box-list-item-label-{id}-{i}\" class=\"cblItemLabel form-check-label\" for=\"{ModelName}_{i}__IsChecked-{id}\">\r\n"
                + $"\t\t\t\t&nbsp; {item.Value}\r\n"
                + "\t\t\t</label>\r\n"
                + $"\t\t\t<input type=\"hidden\" id=\"{ModelName}_{i}__IsChecked-{id}-tag\" name=\"{ModelName}[{i}].IsChecked\" form =\"{FormId}\" value=\"false\">\r\n"
                + $"\t\t\t<input type=\"hidden\" id=\"{ModelName}_{i}__Key-{id}\" name=\"{ModelName}[{i}].Key\" form =\"{FormId}\" value=\"{item.Key}\">\r\n"
                + $"\t\t\t<input type=\"hidden\" id=\"{ModelName}_{i}__Value-{id}\" name=\"{ModelName}[{i}].Value\" form =\"{FormId}\" value=\"{item.Value}\">\r\n"
                + "\t\t</div>\r\n"
                ;

            output.Content.AppendHtml(html);
        }

        output.Content.AppendHtml("\t</div>\r\n");
        output.Attributes.SetAttribute("id", $"check-box-list-{id}");
        output.Attributes.SetAttribute("class", "cblCheckBoxList");
    }
}

Revealing prototype JS makes the "Check All" box play nice with the others:

// Attach event handlers to controls
$(function () {

    // Toggle child check boxes per the "Check All" check box state
    $("div.cblCheckBoxList").on("click", "input.cblCheckAllInput", function (event) {

        let chkBoxListDiv = $(event.target).closest("div.cblCheckBoxList");
        let chkBoxList = new checkBoxList($(chkBoxListDiv).attr("id"), $(event.target).attr("id"));

        chkBoxList.onCheckAllClick();
    });

    // Sync the "Check All" box w/ the child check boxes' check box states
    $("div.cblCheckBoxList").on("click", "input.cblCheckBox", function (event) {

        let chkBoxListDiv = $(event.target).closest("div.cblCheckBoxList");
        let chkBoxList = new checkBoxList($(chkBoxListDiv).attr("id"), null);

        chkBoxList.onCheckItemClick();
    });
});


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Check Box List
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var checkBoxList = function (checkBoxListDivId, checkAllInputId) {

    this.listDivId = checkBoxListDivId;
    this.allInputId = (checkAllInputId ?? $("#" + this.listDivId).find("input.cblCheckAllInput")?.first()?.attr("id"));
};

checkBoxList.prototype = function () {

    // If a "Check All" type check box is clicked, update the individual child check boxes accordingly
    var onCheckAllClick = function () {

        // Find the "Check All" check box that was clicked
        let checkAllInput = $('#' + this.allInputId);

        // Determine whether the "Check All" check box is checked or unchecked
        let chkd = $(checkAllInput).prop('checked');

        // Get a list of child/item check boxes
        let chks = $('#' + this.listDivId).find('input.cblCheckBox');

        // Make the child/item check boxes match the value of the "Check All" check box
        chks.prop('checked', chkd);
    },

    // If an individual child check box is clicked and a "Check All" type checkbox exists, update it accordingly
    onCheckItemClick = function () {

        if (!((this.allInputId === undefined) || (this.allInputId.length === 0))) {

            // Get an array of check boxes that are NOT checked
            let notChkd = $('#' + this.listDivId).find("input.cblCheckBox:not(:checked)");

            // Update the "Check All" check box accordingly
            $("#" + this.allInputId).prop('checked', (notChkd.length === 0));
        }
    };

    return {
        onCheckAllClick: onCheckAllClick,
        onCheckItemClick: onCheckItemClick
    };
}();

Slap some CSS lipstick on:

/*  For CheckBoxList form control   */
.cblCheckBoxList {
    border: 1px solid #ccc;
    padding: 10px 15px;
    margin-right: 10px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    border-radius: 5px;
}
    .cblCheckBoxList .cblContent {
        height: 150px;
        overflow-y: scroll;
        padding: 0;
        margin: 0;
    }

    .cblCheckBoxList .cblTitle {
        font-weight: bolder;
    }

    .cblCheckBoxList .cblCheckAllLabel {
        margin-bottom: 10px;
    }

    .cblCheckBoxList .cblCheckAllInput {
        margin-bottom: 0;
    }

    .cblCheckBoxList .cblItemLabel {
        margin-bottom: 0;
        font-size: small;
    }

    .cblCheckBoxList .cblCheckBox {
        margin-bottom: 0;
        font-size: small;
    }

And drop the Check Box List onto a page:

@* On the passed in View Model, "IceCreamFlavors" is a property that is a List of type CheckBoxListItem *@
<check-box-list 
    asp-title="Ice Cream Flavors"
    asp-items="Model.IceCreamFlavors"
    asp-model-name="IceCreamFlavors"
    asp-form-id="my-form-id"
    asp-check-all-label="All Flavors"
    >
</check-box-list>

Botta boom, botta bing.


The question might be already answered but I wanted to explain your issue, so others can understand what's happening.

You are not aware that you are already specifying the false value to your input, since you're implementing a bad use of attributes.

Let's take a look at your 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>

So, first. You are creating input elements from an array of Filter. Now let's take a closer look at your input element.

<input type="checkbox" id="@Model.Filters[i].Name" asp-for="@Model.Filters[i].Selected" value="@Model.Filters[i].Selected" checked="@Model.Filters[i].Selected" />

Now, let me explain this.

  1. You are specifying a type, using the type attribute.
  2. You are specifying an id, using the id attribute.
  3. You bind the input to the model, using the asp-for tag helper.
  4. You specify a value for the input, using the value attribute.
  5. Finally, you set the input as checked, with the checked attribute.

If you take a look at the Tag Helpers Documentation, you'll find the relationship between the .Net Type and the Input Type, understanding that:

Checkboxes holds a boolean value, corresponding to the model, and formatted by the tag helper as type="checkbox".

Since you're using the type="checkbox" attribute, the Tag Helper value can only be true or false. So, if we go back and look at the input element, you're already specifying a value to the input. Even though the tag-helper can assign a value to the input, it can't override the one already specified. Therefore, your input, will always have the value you've specified, in this case, a boolean is always false by default.

Now you might think that your input element, has a false value, and for instance, adding the checked="checked" will not change the value to true, since the value attributes, overrides the checked attribute. Causing a bad implementation of both attributes.

Therefore, you must use only one of the attributes. (Either the value or the checked). You can use them, for convenience. But in this case, you must use the default checked attribute. Since you're implementing a Tag Helper, and the input value, have to be of type boolean. And the checked attribute value, returns a boolean and for instance, is the one used by the Tag Helper.

So the implementation provided by @dotnetstep should work, since it only declares the tag helper in the input element. So the Tag Helper, handles itself the corresponding attributes of the input.

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

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.


Building on @dotnetstep's answer, I created a Tag Helper that takes a model of IEnumerable of SelectListItem and generates the fields described in his answer.

Here is the Tag Helper code:

[HtmlTargetElement(Attributes = "asp-checklistbox, asp-modelname")]
public class CheckListBoxTagHelper : TagHelper
{
    [HtmlAttributeName("asp-checklistbox")]
    public IEnumerable<SelectListItem> Items { get; set; }

    [HtmlAttributeName("asp-modelname")]
    public string ModelName { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var i = 0;
        foreach (var item in Items)
        {
            var selected = item.Selected ? @"checked=""checked""" : "";
            var disabled = item.Disabled ? @"disabled=""disabled""" : "";

            var html = $@"<label><input type=""checkbox"" {selected} {disabled} id=""{ModelName}_{i}__Selected"" name=""{ModelName}[{i}].Selected"" value=""true"" /> {item.Text}</label>";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Value"" name=""{ModelName}[{i}].Value"" value=""{item.Value}"">";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Text"" name=""{ModelName}[{i}].Text"" value=""{item.Text}"">";

            output.Content.AppendHtml(html);

            i++;
        }

        output.Attributes.SetAttribute("class", "th-chklstbx");
    }
}

You will need to add the following to the _ViewImports.cshtml file:

@addTagHelper *, <ProjectName>

Then to drop the check list box into your razor view it's as easy as:

<div asp-checklistbox="Model.Brands" asp-modelname="Brands"></div>

You might notice that I'm adding a class attribute to the div to style the box and it's content. Here is the CSS:

.th-chklstbx {
  border: 1px solid #ccc;
  padding: 10px 15px;
  -webkit-border-radius: 5px ;
  -moz-border-radius: 5px ;
  -ms-border-radius: 5px ;
  border-radius: 5px ; 
}
.th-chklstbx label {
    display: block;
    margin-bottom: 10px; 
}