In this article, we will learn how to create a checkbox list in blazor in simple steps.

Complete Source Code on Github

If you are new to Blazor then you must see

Creating Application in simple steps

  1. Open Visual Studio 2019
  2. In the search bar of Visual Studio, we are going to enter text blazor to search. The first result which appears is Blazor App we are going to choose it.
  3. Next step, we will configure the project name, the location where we want to store this project, and set the solution name.
  4. Next, we are going to get 2 hosting models options from that. We are going to choose Blazor Server
  5. Application is Created.

After creating the Application, First, Let’s understand what we are going to develop.

We will create a checkbox list and onchange event of Checkbox we will store checked checkbox values in the different collections, which will be used for displaying.

Now let’s start with adding the ViewModel folder to the project.

Adding ViewModel Folder

Adding ViewModel CheckboxListViewModel  

After Adding ViewModel Folder next, we will add the class name “CheckboxListViewModel“, which will have the List collection property.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BlazorPlayGround1.ViewModel
{
    public class CheckboxListViewModel
    {
        public List<SelectListItem> ListofDevices { get; set; }
    }
}

In following, the step we are going to add a Component.

Adding Component

We are going to add a Component with the name CheckboxListComponent.razor.

Adding Base Class for CheckboxListComponentBase Component.

We will add a class with the name CheckboxListComponentBase, and then we will inherit it with ComponentBase.

Next, we are going to add the CheckboxListViewModel property in the CheckboxListComponentBase component along with the ListofSelectedDevices property which is used to store checked checkbox values.

using System.Collections.Generic;
using BlazorPlayGround1.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BlazorPlayGround1.Pages
{
    public class CheckboxListComponentBase : ComponentBase
    {
        protected CheckboxListViewModel CheckboxListViewModel { get; set; } = new CheckboxListViewModel();

        protected List<SelectListItem> ListofSelectedDevices { get; set; } = new List<SelectListItem>();
    }
}

Next step, we need to call the ListofDevices method inside the OnInitialized method to initialize the CheckboxListViewModel property.

Initializing ListofDevices property in OnInitialized event

Here we have initialized ListofDevices Property in OnInitialized Event of Component.

protected override void OnInitialized()
{
            CheckboxListViewModel.ListofDevices = new List<SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = "Computer",
                    Value = "1"
                },
                new SelectListItem()
                {
                    Text = "Laptop",
                    Value = "2"
                },
                new SelectListItem()
                {
                    Text = "Fridge",
                    Value = "3"
                },
                new SelectListItem()
                {
                    Text = "Dishwasher",
                    Value ="4"
                },
                new SelectListItem()
                {
                    Text = "Television",
                    Value = "5"
                },
                new SelectListItem()
                {
                    Text = "Tablet",
                    Value = "6"
                }
            };
}

After initializing ListofDevices next, we will add another Method to CheckboxListComponentBase class for handling the Checkbox onchange event.

Adding Method to Handle Onchange Event of Checkbox

In this part, we will add the CheckboxChange method called when the “onchange” event is raised from the Checkbox.

ChangeEventArgs  :- Supplies information about an change event that is being raised.

The first Parameter which we are going to send to CheckboxChange Method is ChangeEventArgs.

In the ChangeEventArgs, we will get the value of the Checkbox if it is checked or unchecked.

And other are additional parameters that we are sending from Page (CheckboxListComponent.razor) is deviceid, an id (value) and checkbox name (text) of checked and unchecked Checkbox.

Next, we are casting the ChangeEventArgs object to bool and validating if the value is true. Then, we will add it to the ListofSelectedDevices collection and if false, then removing value from ListofSelectedDevices.

Using the StateHasChanged method to notify Component that state is changed.

protected void CheckboxChange(ChangeEventArgs e, string deviceId, string deviceName)
{
     var flag = e.Value != null && (bool)e.Value;
     if (flag)
     {
         ListofSelectedDevices.Add(new SelectListItem()
         {
             Value = deviceId,
             Text = deviceName
         });
     }
     else
     {
         var itemToRemove = ListofSelectedDevices.Single(d => d.Value == deviceId);
         ListofSelectedDevices.Remove(itemToRemove);
     }
     this.StateHasChanged();
 }

Complete CheckboxListComponentBase.cs code behind code

using System.Collections.Generic;
using System.Linq;
using BlazorPlayGround1.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BlazorPlayGround1.Pages
{
    public class CheckboxListComponentBase : ComponentBase
    {
        protected CheckboxListViewModel CheckboxListViewModel { get; set; } = new CheckboxListViewModel();

        protected List<SelectListItem> ListofSelectedDevices { get; set; } = new List<SelectListItem>();

        protected override void OnInitialized()
        {
            CheckboxListViewModel.ListofDevices = new List<SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = "Computer",
                    Value = "1"
                },
                new SelectListItem()
                {
                    Text = "Laptop",
                    Value = "2"
                },
                new SelectListItem()
                {
                    Text = "Fridge",
                    Value = "3"
                },
                new SelectListItem()
                {
                    Text = "Dishwasher",
                    Value ="4"
                },
                new SelectListItem()
                {
                    Text = "Television",
                    Value = "5"
                },
                new SelectListItem()
                {
                    Text = "Tablet",
                    Value = "6"
                }
            };
        }

        protected void CheckboxChange(ChangeEventArgs e, string deviceId, string deviceName)
        {
            var flag = e.Value != null && (bool)e.Value;

            if (flag)
            {
                ListofSelectedDevices.Add(new SelectListItem()
                {
                    Value = deviceId,
                    Text = deviceName
                });
            }
            else
            {
                var itemToRemove = ListofSelectedDevices.Single(d => d.Value == deviceId);

                ListofSelectedDevices.Remove(itemToRemove);
            }

            this.StateHasChanged();
        }
    }
}

Next, we will work on CheckboxListComponent.razor page, which we have added earlier.

CheckboxListComponent.razor page

  1. Going to add the @page Razor directive and specify the route for Component (CheckboxList)
  2. Adding @inherits directive and set base class for component (CheckboxListComponentBase).
  3. Using the Foreach loop, we will add multiple Checkboxes and assign ChangeEventArgs, Value and Text parameters to CheckboxChange Method.
@foreach (var electronic in CheckboxListViewModel.ListofDevices)
{
    <tr>
        <td>@electronic.Text</td>
        <td>
          <input type="checkbox" @onchange="@(x => CheckboxChange(x, electronic.Value, electronic.Text))"/>
        </td>
    </tr>
}

4. At last, we are looping ListofSelectedDevices to display a value that is checked.

 @if (ListofSelectedDevices != null && ListofSelectedDevices.Any())
 {
     <table class="table table-bordered">
         <thead>
             <tr>
                 <th>Selected DeviceId</th>
                 <th>DeviceName</th>
             </tr>
         </thead>
         <tbody>
             @foreach (var selectedDevice in ListofSelectedDevices)
             {
                 <tr>
                     <td>@selectedDevice.Value</td>
                     <td>@selectedDevice.Text</td>
                 </tr>
             }
         </tbody>
     </table>
 }

Now let’s see the complete source code of the CheckboxListComponent Page.

Complete Source Code of the CheckboxListComponent Page

@page "/CheckboxList"
@inherits CheckboxListComponentBase

<div class="col-md-12">

    <div class="card">
        <div class="card-header">
            <h5 class="card-title">CheckboxList</h5>
        </div>
        <div class="card-body">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-4">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>DeviceName</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var electronic in CheckboxListViewModel.ListofDevices)
                                {
                                    <tr>
                                        <td>@electronic.Text</td>
                                        <td>
                                            <input type="checkbox" @onchange="@(x => CheckboxChange(x, electronic.Value, electronic.Text))" />
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>

                    <div class="col-md-4">
                        @if (ListofSelectedDevices != null && ListofSelectedDevices.Any())
                        {
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Selected DeviceId</th>
                                        <th>DeviceName</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var selectedDevice in ListofSelectedDevices)
                                    {
                                        <tr>
                                            <td>@selectedDevice.Value</td>
                                            <td>@selectedDevice.Text</td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        }

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

In the Next Step, Let Press F5 to run the project, and you will see the output.

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.