In this article I will explain with an example, how to implement CheckBoxes (CheckBoxList) in ASP.Net Core Razor Pages.
Group of multiple CheckBoxes (CheckBoxList) will be populated from SQL Server Database by looping through the Model.
The CheckBoxes are grouped by specifying common name for all CheckBoxes, this helps fetching their values as a collection in the Request header.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Database
This article makes use of a table named Fruits whose schema is defined as follows.
ASP.Net Core Razor Pages: CheckBoxes (CheckBoxList) example
 
The Fruits table has the following records.
ASP.Net Core Razor Pages: CheckBoxes (CheckBoxList) example
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Model
This article uses SelectListItem class as Model which is an in-built ASP.Net Core class. It has all the properties needed for populating a list of CheckBoxes.
 
 
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
 
 
Razor PageModel (Code-Behind)
The PageModel consists of two Action Handler methods.
Handler method for handling GET operation
Inside this Handler method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list of FruitModel class is populated.
Finally, the list of Fruits is returned.
 
Handler method for handling Button Click and POST operation
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
When the Form is submitted, the ID of selected Fruits are captured in the Fruit parameter.
Then a loop is executed over the generic list of SelectListItem class objects and the selected Fruit names are set into a ViewData object which will be later displayed in View using JavaScript Alert Message Box.
public class IndexModel : PageModel
{
    public List<SelectListItem> Fruits { get; set; }
 
    public void OnGet()
    {
        //Populate Model from Database.
        this.Fruits = PopulateFruits();
    }
 
    public void OnPostSubmit(string[] fruit)
    {
        //Populate Model from Database.
        this.Fruits = PopulateFruits();
 
        string message = "Selected Items:\\n";
        foreach (SelectListItem item in this.Fruits)
        {
            if (fruit.Contains(item.Value))
            {
                //Fetch the TEXT value.
                item.Selected = true;
                message += string.Format("{0}\\n", item.Text);
            }
        }
 
        //Set the value in ViewData.
        ViewData["Message"] = message;
    }
 
    private static List<SelectListItem> PopulateFruits()
    {
        string constr = @"Data Source=.\SQL2019;Initial Catalog=AjaxSamples;Integrated Security=true";
        List<SelectListItem> items = new List<SelectListItem>();
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = " SELECT FruitName, FruitId FROM Fruits";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        items.Add(new SelectListItem
                        {
                            Text = sdr["FruitName"].ToString(),
                            Value = sdr["FruitId"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }
        return items;
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form with a Submit Button.
Inside the Form, a loop is executed over the generic list of SelectListItem class which in turn generates a list containing a group of HTML CheckBoxes and HTML Label elements.
Note: The CheckBoxes are grouped by keeping the Name attribute value constant for all CheckBoxes.
 
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
 
When the Submit Button is clicked, the Form gets submitted and the values of the selected CheckBoxes are sent to the PageModel.
Finally, the selected Fruit names are displayed using JavaScript Alert Message Box.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_CheckBoxList.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post">
        <table>
            @foreach (var fruit in Model.Fruits)
            {
                <tr>
                    <td>
                        <input id="@fruit.Value" type="checkbox" name="Fruit" value="@fruit.Value" checked="@fruit.Selected"/>
                    </td>
                    <td>
                        <label for="@fruit.Value">@fruit.Text</label>
                    </td>
                </tr>
            }
        </table>
        <br/>
        <input type="submit" value="Submit" asp-page-handler="Submit"/>
    </form>
    @if (ViewData["Message"] != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewData["Message"]");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: CheckBoxes (CheckBoxList) example
 
 
Downloads