'How prevent Blazor EventCallback reset selected item to default value

I have a problem with the return event of a child component on Blazor.

I am currently using MudBlazor, I have created a component called BrandSelect which loads a list of brands that the user can select.

The Brand class I use in the select have of two variables: Id and Name.

This is the code of BrandSelect component:

@inject IBrandService brandService

<MudSelect Value="@SelectedBrand" ValueChanged="OnValueChanged" T="int">
    @foreach (var item in brands)
    {
        <MudSelectItem T="int" Value="@item.Id">@item.Name</MudSelectItem>
    }
</MudSelect>

@code {

    [Parameter]
    public int SelectedBrand { get; set; }

    [Parameter]
    public EventCallback<int> SelectedBrandChanged { get; set; }

    private IEnumerable<Brand> brands;

    protected override async Task OnInitializedAsync()
    {
        brands = await brandService.GetAll(); //Reading the brand from database
        if(brands.Any() && SelectedBrand == 0)
        {
            SelectedBrand = brands.First().Id;
        }
    }

    private async Task OnValueChanged(int value)
    {
        SelectedBrand = value;
        await SelectedBrandChanged.InvokeAsync(SelectedBrand);
    }
}

This is the code of the page where i use my BrandSelect component:

<BrandSelect @ref="brandSelect" SelectedBrand="0" SelectedBrandChanged="LoadBrandPlanning" />

@code {
    private async void LoadBrandPlanning()
    {
        if(brandSelect.SelectedBrand > 0)
        {
            //Do some stuff
        }
    }
}

When the user selects a brand, the data returns correctly to the LoadBrandPlanning function but the item selected of BrandSelect will remain the old value.

How can I solve?



Solution 1:[1]

Try in your MudSelectItem try to use @key="item.Id":

How does @key work

Blazor in the first generates the expected DOM and compares then the current one with the new DOM and then applies the diff. The previous algorithm uses by default the element index for comparing but this doesn't work always correct specially when you have a collection of element like li because it will insert the last one without seeing the changes in the data, when you add the @key it will use a specific key to compare elements instead of using the index.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user13256346