Search code examples
visual-studio-2019blazorbootstrap-selectbootstrap-selectpicker

How to use Bootstrap-select in Blazor Server App


I want to use Bootstrap-select in Blazor Server app, i did all steps from Bootstrap-select website(https://developer.snapappointments.com/bootstrap-select/) to my blazor server app and also install bootstrap-select package from NuGet package manager but there is no effect to select element. Is it possible to use Bootstrap-select in blazor app. I will be very thankful if somebody help.

enter image description here enter image description here It is my razor Component:

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

Solution

  • You have used the library javascript files but are missing multiple dependencies: jQuery and bootstrap js files. bootstrap-select requires Bootstrap js and Bootstrap js requires jQuery and popper.js

    You need to read this on how to fully add bootstrap js files. After that you can use any other Bootstrap based javascript library.

    Preferably, you will also need to call the bootstrap-select init code after the page has rendered.

    See the below javascript code:

    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());
        });    
    }
    

    Note the changed.bs.select event being called. which will get the selected value.

    See the razor file with c# code to init and callback selected value:

    // 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();
    }
    

    Complete source code here