How to create a Checkbox List in Blazor

During my course of developing Blazor based application was that Blazor doesn't have a checkbox list control out of box, so I thought why not create one of my own. so in this blog I will giving a step by step guide to create CheckBox List in Blazor.

Step-1 :  I will be using our Blazor Example project which have created in my previous Blogs this and this about Futuristic Blazor application Architecture. You can get the code from here

Step-2 : Open the BlazorComponents Project, right click on the Shared folder and select Option Add => Razor Component like below screenshot.

Step-3 : On selecting that option you will get following screen, give the name of the component as CheckBoxList as shown in screenshot.

Step-4 : Copy and past following code into the file:

@typeparam TItem
<div style=@Style>
    @if (Data != null)
    {
        foreach (var item in Data)
        {
            var Text = TextField?.Invoke(item);
            var Value = ValueField?.Invoke(item).ToString();
            bool Checked = false;
            if (SelectedValues.Contains(Value))
            {
                Checked = true;
            }
            <input type="checkbox" checked=@Checked
                   @onchange="eventArgs => { CheckboxClicked(Value, eventArgs.Value); }" />
            @Text <br />
        }
    }
    @ChildContent
</div>

@code {
    //Data for the Checkbox 
    [Parameter] public IEnumerable<TItem> Data { get; set; }
    // The field to be shown adjacent to checkbox
    [Parameter] public Func<TItem, string> TextField { get; set; }
    // The Value which checkbox will return when checked 
    [Parameter] public Func<TItem, object> ValueField { get; set; }
    // CSS Style for the Checkbox container 
    [Parameter] public string Style { get; set; }
    // Any childd content for the control (if needed)
    [Parameter] public RenderFragment ChildContent { get; set; }
    // The array which contains the list of selected checkboxs 
    [Parameter] public List<string> SelectedValues { get; set; }

    //Method to update the selected value on click on checkbox 
    public void CheckboxClicked(string aSelectedId, object aChecked)
    {
        if ((bool)aChecked)
        {
            if (!SelectedValues.Contains(aSelectedId))
            {
                SelectedValues.Add(aSelectedId);
            }
        }
        else
        {
            if (SelectedValues.Contains(aSelectedId))
            {
                SelectedValues.Remove(aSelectedId);
            }
        }
        StateHasChanged();
    }
}

Let's understand the above code, the HTML part is basically code to generate the CheckBoxList on the basis of parameter Data which is a list of generic type TItem so that we can bind any object type list to the CheckBoxList. While creating the CheckBoxList the code also checks if the value is present in the SelectedValues list and mark the CheckBox Checked property based on that. This is basically for loading the checkbox list in edit mode. 

I have taken these properties from SelectList control present in Blazorise UI library.The Idea is to make this control part of that library some day.

Step-5:  To use this CheckboxList control, create a new page Named CbListEx.razor in Pages folder following Step-2 & 3.

Step-6: Right click on the Pages folder again and select Option Add => Class like below screenshot.

Step-7: On selecting that option you will get following screen, give the name of the class as CbListEx.razor.cs as shown in screenshot.

The Idea here is to create a code behind class for the razor page and when we give the same name with .cs extension Visual Studio Automatically group the files together like as shown in below screenshot

Step-8: Copy following code in CbListEx.razor.cs file:

using Microsoft.AspNetCore.Components;
using System.Collections.Generic;

namespace BlazorComponents.Pages
{
    public class CbListExBase : ComponentBase
    {
        public List<Employee> EmployeeList { get; set; }
        protected List<string> SelectedIds = new List<string>();
        public List<Employee> ObjectList { get; set; }
        public string OutPutValue { get; set; }
        protected override void OnInitialized()
        {
            EmployeeList = GetMockEmployees();
        }

        protected void ShowSelectedValues()
        {
            OutPutValue = string.Join(",", SelectedIds.ToArray()); 
            StateHasChanged();
        }
        private List<Employee> GetMockEmployees()
        {

            var vSubOne = new Employee()
            {
                EmployeeId = 4,
                FirstName = "S Ravi",
                LastName = "Kumar",
                MobileNo = "9901091975",
                Email = "SKumar@gmail.com"
            };
            var vSubTwo = new Employee()
            {
                EmployeeId = 6,
                FirstName = "Payal",
                LastName = "Jain",
                MobileNo = "9001091905",
                Email = "PJain@gmail.com"
            };
            var vSubThree = new Employee()
            {
                EmployeeId = 7,
                FirstName = "Alok",
                LastName = "Ojha",
                MobileNo = "900091905",
                Email = "AOjha@gmail.com"
            };
            var vSubFour = new Employee()
            {
                EmployeeId = 9,
                FirstName = "Divya",
                LastName = "Bharti",
                MobileNo = "9111767895",
                Email = "DBharti@gmail.com"
            };
            var vSubFive = new Employee()
            {
                EmployeeId = 10,
                FirstName = "Mayuri",
                LastName = "Kango",
                MobileNo = "9111000025",
                Email = "MKango@gmail.com"
            };
            var vSubSix = new Employee()
            {
                EmployeeId = 11,
                FirstName = "Tamraj",
                LastName = "Kilwish",
                MobileNo = "9251000025",
                Email = "TKilwish@gmail.com"
            };
            var vSubSeven = new Employee()
            {
                EmployeeId = 12,
                FirstName = "James",
                LastName = "Bond",
                MobileNo = "9521000025",
                Email = "James007@gmail.com"
            };

            var vSubList = new List<Employee>
        {
                vSubOne, vSubTwo,
                vSubThree, vSubFour,
                vSubFive,vSubSix,
                vSubSeven
            };

            return vSubList;
        }
    }

	public class Employee
	{
		public long EmployeeId
		{ get; set; }

		public string FirstName
		{ get; set; }

		public string LastName
		{ get; set; }

		public string FullName
		{
			get
			{
				return FirstName + " " + LastName;
			}
		}
		public string MobileNo
		{ get; set; }
		public string Email
		{ get; set; }

	}

}

In above code we are basically loading the CheckBoxList on page Load with a list of Employee object which is a custom class. ShowSelectedValues method will be called on click of a button to show the selected values of the checkbox.

I have kept the Employee class in same file just to save file in actual project it will be part of your Models Folder/project

Step-9: Copy Paste following code in CbListEx.razor file :

@page "/CbListEx"
@inherits CbListExBase
    <div class="col-12">
        <h3><b>CheckBox List Example </b></h3>
        <hr />
        <div class="col-12 row">
            <label class="col-2 font-weight-bold">CheckBox List :</label>
            <CheckBoxList Data="@EmployeeList"
                          TextField="@((item)=>item.FullName)"
                          ValueField="@((item)=>item.EmployeeId)"
                          SelectedValues="@SelectedIds" />
        </div>
        <div class="col-12 row">
            <label class="col-2 font-weight-bold">Selected Ids :</label>
            <b>@OutPutValue</b>
        </div>
        <br />
        <div class="col-12 row">
            <span class="col-2"></span>
            <button class="form-control col-1 btn btn-primary" @onclick="ShowSelectedValues">Show Checked Values</button>
        </div>
    </div>

In above code we are just showing the binded CheckBoxList , a button to show the selected values in a Label.

Step-10: Add following code in NavMenu.razor inside the Shared folder to add a menu item for opening CbListEx.razor page.

        <li class="nav-item px-3">
            <NavLink class="nav-link" href="CbListEx">
                <span class="oi oi-list-rich" aria-hidden="true"></span> CheckBox List Example
            </NavLink>
        </li>

Now when you execute the application you will get following output: 


In this blog we learned about how create CheckBox List in Blazor which can be used in both  Blazor server as well as Blazor WebAssembly application. The code of this project template is available here at Github


S Ravi Kumar

Ravi is an experienced IT professional with over 15 years of IT services experience using Microsoft technologies including like ASP.Net, C#, .Net Core, Xamarin.Forms, Azure etc.

Add a new comment

 

Comments