Code Snippet to Create a Checkbox List in an ASP.NET Core Razor Page Application

Checkbox lists are helpful when you want to allow users to select more than one predefined option. This article explains how a Checkbox list can be generated, and the selected checkbox values can be retrieved when the page is submitted in an ASP.NET Core Razor Page application. The sample code related to this can be downloaded from Github

In the following example, a class named Skill is defined with properties SkillID and SkillName to store a list of skills that will be bind to the Checkbox list.

Razor PageModel

The page model contains two action handler methods OnGet and OnPost.

OnGet Handler

The OnGet handler contains code to initialize Skills collection and add a set of skills to the collection. This collection is then assigned to another collection of type IList<SelectListItem> and is used to generate the Checkbox list. The SkillId property is assigned to the Value property of the SelectListItem, and the SkillName is assigned to the Text property of it. 

OnPost Handler

The OnPost handler contains the code to be executed when the page is submitted. There, we loop through the IList<SelectListItem> collection to retrieve the Id and name of the selected skills. It is then assigned to a variable to display on the page. 

 

    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        public class Skill
        {
            public int SkillID { get; set; }
            public string SkillName { get; set; }
        }
        [BindProperty]
        public IList<SelectListItem> Skills { get; set; }
        [TempData]
        public string SelectedSkills { get; set; }
        [TempData]
        public string SelectedSkillIDs { get; set; }
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }
        public void OnGet()
        {
            List<Skill> SkillList = new List<Skill>(){
             new Skill { SkillID = 1, SkillName = "Communication" },
            new Skill {SkillID = 2, SkillName = "Decision-Making" },
            new Skill {SkillID = 3, SkillName = "Flexibility" },
            new Skill {SkillID = 4, SkillName = "Innovation" },
            new Skill {SkillID = 5, SkillName = "Integrity" },
            new Skill {SkillID = 6, SkillName = "Leadership" },
            new Skill {SkillID = 7, SkillName = "Time Management" },
            new Skill {SkillID = 8, SkillName = "Negotiation" }
        };

            Skills = SkillList.ToList<Skill>().Select(m => new SelectListItem { Text = m.SkillName, Value = m.SkillID.ToString() }).ToList<SelectListItem>();
          
        }
        public IActionResult OnPost()
        {
            foreach (SelectListItem skill in Skills)
            {
                if (skill.Selected)
                {
                    SelectedSkills = $"{skill.Text},{SelectedSkills}";
                    SelectedSkillIDs= $"{skill.Value},{SelectedSkillIDs}";
                }
            }
            SelectedSkills = SelectedSkills.TrimEnd(',');
            SelectedSkillIDs = SelectedSkillIDs.TrimEnd(',');
            return RedirectToPage("index");            
        }
    }

Razor Page View

The view file contains the razor syntax to generate the Checkbox list. We loop through the IList<SelectListItem> collection and generate the checkboxes using asp-for tag helpers. Two hidden controls are used to store the Text and Value fields as this is essential to get the selected checkbox's texts and values when the form is submitted.

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<form method="post">
    <div class="text-left">
        <h1 class="display-4">Welcome</h1>
        <br />
        <br />
        @if (Model.SelectedSkills != null)
        {
            <h5>Selected Skills:@Model.SelectedSkills </h5>
            <h5>Selected Skill Ids :@Model.SelectedSkillIDs </h5>
            <br />
        }
        @{ for (int i = 0; i < Model.Skills.Count; i++)
            {
                var j = i + 1;
                <input asp-for="@Model.Skills[i].Value" type="hidden" />
                <input asp-for="@Model.Skills[i].Text" type="hidden" />
                {
                    <input asp-for="@Model.Skills[i].Selected" /> @Model.Skills[i].Text
                }

                if (j % 3 == 0 )
                {
                    <br />
                }
            }
        }

        <div class="form-group mt-2">
            <input type="submit" value="Submit" class="btn btn-primary" />
        </div>
    </div>
</form>

 

Screenshot

 


Search