Search code examples
c#selectbindingblazor-webassembly

Blazor WASM, updating data changes automatically


I have a Blazor WASM project. The index.razor page loops through an array of objects (repair orders) and builds a table with each element of the array. Each row of the table contains 2 <select> fields so the data for properties of each object can be changed directly from the table without actually opening the edit page.

I am using SignalR to automatically update all the connected clients when someone changes an item. So I need to call a function to update the database and send the SignalR message, when a user changes a <select> option

I am using @onselectionchange="() => SelectionChanged(ro)" in the <select>.

I put a break point at the entry of SelectionChanged(ro). The app never calls the function from @onselectionchange="() => SelectionChanged(ro)".

What options do I have to get this to work?

Table Code:

@foreach (var ro in repairOrders)
        {
            <tr>
                <td>@ro.Tag</td>
                <td>@ro.Control</td>
                <td>@ro.Customer</td>
                <td>
                   
                    <select class="form-control" id="location" @bind="@ro.Location" @onselectionchange="() => SelectionChanged(ro)">
                    <option value="">Select Location</option>
                        @foreach(var loc in locationOptions)
                        {
                            <option value="@loc.Name">@loc.Name</option>
                        }
                    </select>
                </td>
                <td>

C# Code:

protected async Task SelectionChanged(RepairOrder _ro)
{
    await Http.PutAsJsonAsync("api/RepairOrders/" + _ro.Id.ToString(), _ro);
    if (IsConnected) await SendMessage();
}

Solution

  • You have only one tiny error in your code.

    The onselectionchange is an event fired when a user selects a text. Hence, your method is not run.

    You can instead choose the event onchange like

    <select @bind="..." 
    @bind:event="oninput" 
    @onchange="(x) =>  SelectionChanged(to)" ...>
    

    With @bind:event="oninput" Blazor writes back to the binding as soon as something is updated. This is triggered before @onchange, so you have the updated value ready in your model.