【问题标题】:How to use Bootstrap-select in Blazor Server App如何在 Blazor Server 应用程序中使用 Bootstrap-select
【发布时间】:2020-10-29 01:21:23
【问题描述】:

我想在 Blazor Server 应用程序中使用 Bootstrap-select,我完成了从 Bootstrap-select 网站 (https://developer.snapappointments.com/bootstrap-select/) 到我的 blazor 服务器应用程序的所有步骤,还从 NuGet 包管理器安装了 bootstrap-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>

【问题讨论】:

    标签: visual-studio-2019 blazor bootstrap-select bootstrap-selectpicker


    【解决方案1】:

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

    您需要阅读this,了解如何完全添加引导 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。这将获得选定的值。

    使用 c# 代码查看 razor 文件以初始化和回调选定的值:

    // 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

    【讨论】:

    • 从js调用时,如果将值转换为字符串,则可以支持multiple属性。 dotnetHelper.invokeMethodAsync(callbackMethodName, String($(pickerElementName).val()));
    猜你喜欢
    • 2021-04-16
    • 2020-04-03
    • 2020-11-05
    • 2021-11-04
    • 1970-01-01
    • 2020-08-18
    • 2020-10-16
    • 2023-02-06
    • 1970-01-01
    相关资源
    最近更新 更多