This article shows how to build a custom Custom component to handle checkbox after confirmation modal popup using .NET Blazor.
Introduction
In one of my assignments where we were using Blazor.net, few of the forms had input control as checkbox. As per the requirement, it was difficult to handle the checkbox value after the change event using InputCheckBox
component in EditForm
or <\input type="checkbox" />
. Listed below is some of the logic which restricted using the default component:
- Revert the value of checkbox after the click of confirmation modal popup
- Handle the above functionality with minimal code handling
To achieve the above functionality, it was required to create a custom component which will handle the checkbox single handedly and avoid code duplication. The component uses third party package, i.e., Blazored Modal which is freely available Nuget package manager. Detailed configuration provided on their site can be reference to integrate the same in application. This can be replaced as per the usage in the application.
Below is the code for the same along with the explanation of how to use it in different scenarios.
Using the Code
The code works like a simple plugin by just configuring the component and using it in the application. Below is the code for the same.
Startup.cs
Add service reference to blazored modal. Blazored modal related configuration.
services.AddBlazoredModal();
App.razor
Wrap the router tag with CascadingBlazoredModal
. Blazored modal related configuration.
<CascadingBlazoredModal>
<Router AppAssembly="@typeof(Program).Assembly">
.....
</Router>
</CascadingBlazoredModal>
_Host.cshtml
Provide reference to Blazored Modal script and style sheet. Blazored modal related configuration.
<link href="_content/Blazored.Modal/blazored-modal.css" rel="stylesheet" />
<script src="_content/Blazored.Modal/blazored.modal.js"></script>
ConfirmationCheckBox.razor
Create a razor component as per the below code at a shared UI folder of the project. For example, BlazorApp/Pages/Component.
<div class="@Class">
<input class="checkbox" type="checkbox" id="@Id"
checked="@Value"
@bind-value="Value"
@bind-value:event="oninput"
@onchange="OnChecked"
readonly="@ReadOnly"
/>
<label for="@Id"><span></span></label>
</div>
ConfirmationCheckBox.razor.cs
Create a razor.cs class same as above in the same folder as that of razor component. The below code acts as a backend code for the razor page created.
#region System References
using System;
using System.Threading.Tasks;
#endregion
#region BlazorApp Reference
using BlazorApp.Pages.Modal;
using Blazored.Modal;
using Blazored.Modal.Services;
#endregion
#region Microsoft References
using Microsoft.AspNetCore.Components;
#endregion
namespace BlazorApp.Pages.Components
{
public partial class ConfirmationCheckBox
{
#region Parameter
[Parameter] public string Class {get;set;}
[Parameter] public string Name {get;set;}
[Parameter] public string PopupMessageForTrue {get;set;}
[Parameter] public string PopupMessageForFalse {get;set;}
[Parameter] public EventCallback<bool> OnPopupClicked {get;set;}
[Parameter] public bool ReadOnly {get;set;}
[Parameter] public string Id {get;set;}
[Parameter] public bool? Value{
get=>_value;
set{
if(_value==value) return;
_value=value;
ValueChanged.InvokeAsync(value);
}
}
[Parameter] public EventCallback<bool?> ValueChanged {get;set;}
#endregion
#region Inject
[Inject] IModalService Modal {get;set;}
#endregion
bool? _value;
string Message;
#region Protected Method
protected override void OnInitialized(){
Class=string.IsNullOrEmpty(Class)?"checkbox":Class;
}
#endregion
#region Private Method
private async Task OnChecked(ChangeEventArgs args){
bool argsValue=Convert.ToBoolean(args.Value);
Message= !argsValue ? PopupMessageForTrue : PopupMessageForFalse;
Message = string.IsNullOrEmpty(Message) ? "Are you sure ?" : Message;
var options= new ModalOptions()
{DisableBackgroundCancel=true,HideCloseButton=true};
ModalParameters parameter = new ModalParameters();
parameter.Add("Body", Message);
var formModal = Modal.Show<ConfirmationModal>("Confirm", parameter,options);
var result= await formModal.Result;
if(!result.Cancelled){
if(Convert.ToBoolean(result.Data))
await ValueChanged.InvokeAsync(argsValue);
else
await ValueChanged.InvokeAsync(!argsValue);
await OnPopupClicked.InvokeAsync(Convert.ToBoolean(result.Data));
}
StateHasChanged();
}
#endregion
}
}
Below is the description of each and every variable and function:
Component Attribute | Description |
Value | The model property to be passed |
Name | Name aligned to the checkbox component |
ValueChanged | Event call back which sets the model property on change of the value. Helps in two way binding |
Id | id attribute of the component to be set |
Class | class attribute of div that wraps the input checkbox |
ReadOnly | disable attribute to be set, i.e., disabled if true else enabled |
PopupMessageForTrue | Message to be displayed on modal popup if checkbox is checked |
PopupMessageForFalse | Message to be displayed on modal popup if checkbox is un-checked |
Method | Description |
OnInitializedAsync | Method to be executed on initialization of the component |
OnChecked | Method to be called on checkbox check of the input field |
How to Use?
Below is the set of sample code that shows how to use the above component using two way binding.
ConfirmCheckBox.razor
Below is the sample code that displays how to use the able component.
@page "/ConfirmationCheckBox"
<div class="container">
<div class="col-12">
<div class="row">
<div class="form-group">
<ConfirmationCheckBox
@bind-Value="@CheckBoxValue"
OnPopupClicked="@((value)=>PopupClicked(value))"
PopupMessageForTrue="Are You sure ? It is checked."
PopupMessageForFalse="Are You sure ? It is unchecked." />
</div>
</div>
<div class="row">
<p>CheckBoxValue : @CheckBoxValue</p>
</div>
<div class="row">
<p>Popup Value : @PopupValue</p>
</div>
</div>
</div>
@code{
private bool? CheckBoxValue{get;set;}
private bool? PopupValue {get;set;}
/// <summary>
/// Method to be invoked on popup action by ConfirmationCheckBox component
/// </summary>
/// <param name="value">bool</param>
/// <returns></returns>
private void PopupClicked(bool value){
PopupValue=value;
}
}
The sample code is available on GitHub.
If any of the readers have an improved and better workflow for the above requirement, I would like to add the same to my knowledge.
CODE IT !!!
History
- 6th June, 2021: Initial version