Blazor Jquery Select2 Not Working

Jquery Select2 does not get applied due to DOM render issue in Blazor

October 17, 2020

In this article we will resolve below mentioned issues related to Jquery Select2 in Blazor Web Assembly Application

1) Jquery Select2 Runs before blazor DOM gets ready. Because of this Select2 does not apply to Select Input.

2) The blazer Change event does not work with two way binding

3) Model Property does not update

Below mentioned code resolves all the issues mentioned.

Jquery Code

$(document).ready(function () {
    Reload();
});
 
function Reload() {
    $('.select2').select2({
        placeholder: "Select,
        allowClear: true
    }).on('select2:unselecting'function () {
        $(this).data('unselecting'true);
    }).on('select2:opening'function (e) {
        if ($(this).data('unselecting')) {
            $(this).removeData('unselecting');
            e.preventDefault();
        }
    }).on('change.select2'function (e) {
        var selectedVal = e.target.value;
        DotNet.invokeMethodAsync('BlazorApp''UpdateModel', selectedVal);
        //BlazorApp - Your Application DLL Name
        //UpdateModel - Function Name [JSInvokable]
    });;
}

Razor HTML

@if (countryModel != null)
{
    <select @bind="countryModel.Country_Id" class="select2">
        <option value="0">Select Country</option>
        @foreach (var country in countryModel.List_Country)
        {
            if (country != null)
            {
                <option value="@country.Country_Id">@country.Country_Title</option>
            }
        }
    </select>
}

Razor Code

[Inject]
public IJSRuntime JSRuntime { getset; }
 
private static Action<string> countryAction;
 
public Country countryModel = new Country();
protected override async Task OnInitializedAsync()
{
    countryAction = UpdateModelData;
    countryModel.List_Country = new List<Country>(); // Populate data from apis
 
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (countryModel != null)
    {
        await JSRuntime.InvokeVoidAsync("Reload").AsTask();
    }
}
 
private void UpdateModelData(string value)
{
    countryModel.Country_Id = int.Parse(value);
    StateHasChanged();
}
 
[JSInvokable]
public static void UpdateModel(string value)
{
    countryAction.Invoke(value);
}

Post Comments(2)

kamal timalsinsAugust 30, 2021

in my case not working

MalikNovember 23, 2021

What if you have multiple Select2 Dropdowns on single Razor Component and also if you have Multi-Value select2 List how you will handle these two scenarios...Can you also add example of that.

Leave a reply

Will not be displayed in comment box .

Loading...