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 { get; set; } 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)
in my case not working
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.