In this article I will explain with an example, how to implement CheckBoxList (List of CheckBoxes) in ASP.Net Core MVC.
The records from the Database will be fetched from Database Table using ADO.Net into SelectListItem class as Model and a Custom CheckBoxList has been populated in ASP.Net Core MVC.
Note: For beginners in using ADO.Net with ASP.Net Core MVC, please refer my article .Net Core: ADO.Net Tutorial with example.
 
 
Database
This article makes use of a table named Fruits whose schema is defined as follows.
ASP.Net Core MVC: CheckBox (CheckBoxList) example
 
The Fruits table has the following records.
ASP.Net Core MVC: CheckBox (CheckBoxList) example
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 

Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
 
 
Model
This article uses SelectListItem class as Model which is an in-built ASP.Net Core MVC class. It has all the properties needed for populating a CheckBoxList.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list of SelectListItem class is populated.
The FruitName is stored in the Text property while the FruitId is stored in the Value property.
Finally, the list of Fruits are returned to the View.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View when the Submit Button is clicked.
When the Form is submitted, the FruitId 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 ViewBag object which will be later displayed in View using JavaScript Alert Message Box.
Note: For more details on displaying message using JavaScript Alert MessageBox, please refer my article ASP.Net MVC: Display Message from Controller in View using JavaScript Alert MessageBox.
 
public class HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        List<SelectListItem> items = PopulateFruits();
        return View(items);
    }
 
    [HttpPost]
    public IActionResult Index(string[] fruit)
    {
        ViewBag.Message = "Selected Items:\\n";
        List<SelectListItem> items = PopulateFruits();
        foreach (SelectListItem item in items)
        {
            if (fruit.Contains(item.Value))
            {
                item.Selected = true;
                ViewBag.Message += string.Format("{0}\\n", item.Text);
            }
        }
 
        return View(items);
    }
 
    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;
    }
}
 
 
View
Inside the View, in the very first line the generic list of SelectListItem class is declared as Model for the View.
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes and a Submit Button.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the Form, a loop is executed over the generic list of SelectListItem class which in turn generates a list containing HTML CheckBoxes and HTML Label elements.
When the Submit Button is clicked, the Form gets submitted and the values of the selected CheckBoxes are sent to the Controller.
Finally, the selected Fruit names are displayed using JavaScript Alert Message Box.
@model List<SelectListItem>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="Index">
        <table>
            @foreach (var fruit in Model)
            {
                <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"/>
    </form>
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: CheckBox (CheckBoxList) example
 
 
Downloads