如何在 Blazor Server App 中使用 Bootstrap-select

How to use Bootstrap-select in Blazor Server App

我想在 Blazor Server 应用程序中使用 Bootstrap-select,我完成了从 Bootstrap-select 网站 (https://developer.snapappointments.com/bootstrap-select/) 到我的 blazor 服务器应用程序还从 NuGet 包管理器安装 bootstrap-select 包,但对 select 元素没有影响。是否可以在 blazor 应用程序中使用 Bootstrap-select。如果有人帮助,我将不胜感激。

这是我的剃须刀组件:

@page "/"

    <select class="selectpicker" data-live-search="true">
      <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
      <option data-tokens="mustard">Burger, Shake and a Smile</option>
      <option data-tokens="frosting">Sugar, Spice and all things nice</option>
    </select>

您已经使用了库 javascript 文件,但缺少多个依赖项:jQuery 和 bootstrap js 文件。 bootstrap-select 需要 Bootstrap js 和 Bootstrap js 需要 jQuery 和 popper.js

您需要阅读 this 如何完全添加 bootstrap js 文件。之后,您可以使用任何其他基于 Bootstrap 的 javascript 库。

最好,您还需要在页面呈现后调用 bootstrap-select 初始化代码。

见下面javascript代码:

window.InitSelectPicker = (dotnetHelper, callbackMethodName, pickerElementName) => {

    // initialize the specified picker element
    $(pickerElementName).selectpicker();

    // setup event to push the selected dropdown value back to c# code
    $(pickerElementName).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        dotnetHelper.invokeMethodAsync(callbackMethodName, $(pickerElementName).val());
    });    
}

请注意正在调用 changed.bs.select event。这将获得 selected 值。

查看带有 c# 代码的 razor 文件以初始化和回调 selected 值:

// inject jsruntime to call javascript code
[Inject] public IJSRuntime JSRuntime { get; set; }

// hold the callback selected value
public string SelectedValue { get; set; }

// call the javascript method to init the select picker
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender) // only needs to be called once per page render
    {
        await JSRuntime.InvokeVoidAsync("InitSelectPicker", DotNetObjectReference.Create(this), "OnSelectedValue", ".selectpicker");
    }
}

// method which will be triggered by javascript, need to pass the method name 
[JSInvokable]
public void OnSelectedValue(string val)
{
    SelectedValue = val;
    StateHasChanged();
}

完整的源代码here