Checkbox Aria TagHelper

Published: (December 7, 2025 at 04:22 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Introduction

Learn how to initialize all checkbox inputs that reside in an ASP.NET Core page using a custom TagHelper.
The TagHelper evaluates the checked attribute value on page load and adds/sets the aria-checked attribute. This is important for screen readers to assist people with limited or no vision.

How to use

  1. Create the TagHelper
    In an ASP.NET Core project, create a folder named TagHelpers and add the following class:

    using Microsoft.AspNetCore.Razor.TagHelpers;
    
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class CheckboxAriaTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (!output.Attributes.TryGetAttribute("type", out var type) ||
                type.Value.ToString() != "checkbox")
                return;
    
            var isChecked = output.Attributes.TryGetAttribute("checked", out var chk);
            output.Attributes.SetAttribute("aria-checked", isChecked);
        }
    }
  2. Register the TagHelper
    Add the following line to Pages/_ViewImports.cshtml. Replace CheckedListBox with your project’s root namespace.

    @addTagHelper *, CheckedListBox
  3. Add checkbox inputs to a page
    The example below shows how to render a list of checkboxes bound to a model (CheckModels). The TagHelper runs on each <input> of type checkbox.

    @for (var index = 0; index 
                
                
                
                
                
                    
                    
                    
                        @Model.CheckModels[index].Name
                    
                
            
        
    }
  4. Add JavaScript to keep aria-checked in sync
    Place the script in a Scripts section (or any appropriate location) so it runs after the DOM is loaded.

    @section Scripts {
        
            document.addEventListener("DOMContentLoaded", () => {
                document.querySelectorAll("input.js-aria-checkbox[type='checkbox']").forEach(cb => {
                    // Update aria-checked whenever the checkbox changes
                    cb.addEventListener("change", function () {
                        this.setAttribute("aria-checked", this.checked ? "true" : "false");
                    });
                });
            });
        
    }

Testing

  1. Run the page in a browser.
  2. Open Developer Tools.
  3. Select a checkbox input and toggle its state.
  4. Observe that the aria-checked attribute updates to "true" or "false" accordingly.

The TagHelper simplifies setting the aria-checked attribute, providing a better experience for users with vision disabilities.

Back to Blog

Related posts

Read more »