如何在 Blazor 服务器应用程序中使用 Bootstrap-select

Arv*_*vin 1 bootstrap-select bootstrap-selectpicker blazor visual-studio-2019

我想在 Blazor 服务器应用程序中使用 Bootstrap-select,我执行了从 Bootstrap-select 网站(https://developer.snapappointments.com/bootstrap-select/)到我的 blazor 服务器应用程序的所有步骤,并安装了 bootstrap-select 包NuGet 包管理器,但选择元素没有效果。是否可以在 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>
Run Code Online (Sandbox Code Playgroud)

Uma*_*air 6

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

您需要阅读有关如何完全添加 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());
    });    
}
Run Code Online (Sandbox Code Playgroud)

请注意正在调用的changed.bs.select事件。这将获得选定的值。

请参阅 razor 文件,其中包含用于初始化和回调所选值的 C# 代码:

// 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();
}
Run Code Online (Sandbox Code Playgroud)

完整的源代码在这里