天天看點

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

繼續閱讀