天天看点

Blazor确认复选框组件介绍使用代码如何使用?

目录

介绍

使用代码

Startup.cs

App.razor

_Host.cshtml

ConfirmationCheckBox.razor

ConfirmationCheckBox.razor.cs

如何使用?

ConfirmCheckBox.razor

  • 从GitHub下载示例代码

介绍

在我使用Blazor.net的一项作业中,很少有表单将输入控件作为复选框。根据要求,在更改事件之后在EditForm或<\input type="checkbox" />中使用InputCheckBox组件处理复选框值是很困难的。下面列出了一些限制使用默认组件的逻辑:

  1. 点击确认模态弹窗后恢复复选框的值
  2. 以最少的代码句柄来处理上述功能

为了实现上述功能,需要创建一个自定义组件来单独处理复选框并避免代码重复。该组件使用第三方包,即Blazored Modal,它是免费提供的Nuget包管理器。他们网站上提供的详细配置可以参考,以便在应用程序中集成。这可以根据应用程序中的用法进行替换。

下面是相同的代码以及如何在不同场景中使用它的解释。

使用代码

代码就像一个简单的插件,只需配置组件并在应用程序中使用它。下面是相同的代码。

Startup.cs

将服务引用添加到blazored modal。Blazored模态相关配置。

services.AddBlazoredModal();
           

App.razor

用CascadingBlazoredModal包裹路由器标签。Blazored模态相关配置。

<CascadingBlazoredModal>
<Router AppAssembly="@typeof(Program).Assembly">
   .....
</Router>
</CascadingBlazoredModal>
           

_Host.cshtml

提供对Blazored Modal脚本和样式表的参考。Blazored模态相关配置。

<link href="_content/Blazored.Modal/blazored-modal.css" target="_blank" rel="external nofollow"  rel="stylesheet" />
<script src="_content/Blazored.Modal/blazored.modal.js"></script>
           

ConfirmationCheckBox.razor

根据以下代码在项目的共享UI文件夹中创建一个razor组件。例如,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

在razor组件所在的文件夹中创建与上述相同的razor.cs类。以下代码充当创建的Razor页面的后端代码。

#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 for div that wraps the input checkbox
        [Parameter] public string Class {get;set;}
        // Parameter for Checkbox name
        [Parameter] public string Name {get;set;}
        // Parameter to defined message on popup when checkbox is checked
        [Parameter] public string PopupMessageForTrue {get;set;}
        // Parameter to defined message on popup when checkbox is unchecked
        [Parameter] public string PopupMessageForFalse {get;set;}
        // Parameter to defined event call back on Popup button action
        [Parameter] public EventCallback<bool> OnPopupClicked {get;set;}
        // Parameter to make the checkbox readonly
         [Parameter] public bool ReadOnly {get;set;}
        // Parameter to define id of the checkbox
        [Parameter] public string Id {get;set;}
        // Parameter to bind the value of checkbox
        [Parameter] public bool? Value{
            get=>_value;
            set{
                if(_value==value) return;

                _value=value;
                ValueChanged.InvokeAsync(value);
            }
        }
        // Parameter to handle two way binding
        [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
        /// <summary>
        /// Method to change the Check box change event
        /// </summary>
        /// <param name="args">ChangeEventArgs</param>
        /// <returns></returns>
        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
    }
}
           

下面是每个变量和函数的描述:

组件属性 描述
Value 要传递的模型属性
Name 名称与复选框组件对齐
ValueChanged 在值更改时设置模型属性的事件回调。有助于双向绑定
Id 要设置的组件的id属性
Class 包装输入复选框的div类属性
ReadOnly 要设置的禁用属性,即如果true,其他启用则禁用
PopupMessageForTrue 如果选中复选框,将在模态弹出窗口中显示消息
PopupMessageForFalse 如果未选中复选框,将在模态弹出窗口中显示消息
方法 描述
OnInitializedAsync 在组件初始化时执行的方法
OnChecked 在输入字段的复选框检查中调用的方法

如何使用?

下面是一组示例代码,展示了如何使用双向绑定来使用上述组件。

ConfirmCheckBox.razor

下面是显示如何使用能够组件的示例代码。

@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;
        }
}
           

示例代码可在GitHub 上获得。

https://www.codeproject.com/Tips/5304619/Blazor-Confirmation-Checkbox-Component

继续阅读