Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MudBlazor MudSelect updating selected value OnInitializedAsync

Tags:

c#

mudblazor

I have a MudBlazor MudSelect that I am populating with an Id value and a Description from an API and if there is only one item returned I want it to be selected. With my current code the numerical Id shows up as the selection and not the description as it should. As soon as I click on the dropdown (or enter info in any other field) it switches to the Description that I want but that's not enough.

Also of note, before the async call a 0 shows up as selected. How do I get it to be blank to start?

Relevant page section:

<MudSelect T="int" Label="Group Type" @bind-Value="model.GroupTypeId" Validation="@(() => model.GroupTypeId)" AnchorOrigin="Origin.BottomCenter">
    @foreach (GroupTypeModel grouptype in grouptypes)
    {
        <MudSelectItem Value="@grouptype.Id">@grouptype.Description</MudSelectItem>
    }
</MudSelect>

Relevant code section:

@code {
    CreateGroupModel model = new();
    public List<GroupTypeModel> grouptypes { get; set; } = new List<GroupTypeModel>();
    protected override async Task OnInitializedAsync()
    {
        grouptypes = await GroupTypeEndpoint.GetOwned();
        if (grouptypes.Count()==1)
        {
            model.GroupTypeId = grouptypes.First().Id;
            // EDIT - MY FIX HERE:
            StateHasChanged();
        }
    }
}

Any help would be appreciated, thanks!

EDIT: I fixed the main issue by adding a StateHasChanged(); inside the if statement. I would still like help having it default to blank instead of 0 (for all my MudSelect elements with an id).

like image 731
paulguy Avatar asked Oct 30 '25 21:10

paulguy


1 Answers

You can add a MudSelectItem with Value="0" and Disabled="true" that will be selected by default and show a message like "Select group type".

<MudSelect T="int" Label="Group Type" @bind-Value="model.GroupTypeId" Validation="@(() => model.GroupTypeId)" AnchorOrigin="Origin.BottomCenter">
    <MudSelectItem Value="0" Disabled="true">Select group type</MudSelectItem>
    @foreach (GroupTypeModel grouptype in grouptypes)
    {
        <MudSelectItem Value="@grouptype.Id">@grouptype.Description</MudSelectItem>
    }
</MudSelect>

Also in my tests it looks like the call to StateHasChanged() is not needed.

https://try.mudblazor.com/snippet/GYmGOZQbBWLXMnDy

like image 62
Dimitris Maragkos Avatar answered Nov 01 '25 13:11

Dimitris Maragkos