Which event in a MudBlazor MudSelect is called when selection is changed and how would it be implemented?

I'm using MudBlazor and implemented a MudSelect component following the documentation.

However, I'm trying to get the selected value from the MudSelect when a selection has been made but unsure which event to call. Tried a few such as SelectedValuesChanged but nothing is firing in my code block when the selection has been updated.

Using a standard HTML select I would just call @onchange and then write a method for the event. This doesn't work in MudBlazor.

Here is my MudSelect

<MudSelect T="Stage" Label="Stage" Variant="Variant.Filled" AnchorOrigin="Origin.BottomCenter"> <MudSelectItem Value="@(new Stage("Stage 1"))" /> <MudSelectItem Value="@(new Stage("Stage 2"))" /> <MudSelectItem Value="@(new Stage("Stage 3"))" /> <MudSelectItem Value="@(new Stage("Stage 4"))" /> <MudSelectItem Value="@(new Stage("Stage 5"))" />
</MudSelect>

Here's the @code block

public class Stage
{ public Stage(string stageName) { StageName = stageName; } public readonly string StageName; public override bool Equals(object o) { var other = o as Stage; return other?.StageName == StageName; } public override int GetHashCode() => StageName?.GetHashCode() ?? 0; public override string ToString() => StageName;
}

1 Answer

You can use ValueChanged event callback which is fired when the Value property changes.

Implementation:

<MudSelect T="Stage" ToStringFunc="@converter" ValueChanged="OnValueChanged" Label="Stage" Variant="Variant.Filled" AnchorOrigin="Origin.BottomCenter"> <MudSelectItem Value="@(new Stage("Stage 1"))" /> <MudSelectItem Value="@(new Stage("Stage 2"))" /> <MudSelectItem Value="@(new Stage("Stage 3"))" /> <MudSelectItem Value="@(new Stage("Stage 4"))" /> <MudSelectItem Value="@(new Stage("Stage 5"))" />
</MudSelect>
@if(selectedStage is not null)
{ <br/> <MudAlert Severity="Severity.Info">@(selectedStage.StageName) was selected</MudAlert>
}
@code { private Stage selectedStage {get; set;} readonly Func<Stage, string> converter = p => p.StageName; private void OnValueChanged(Stage selected) { selectedStage = selected; // Do other stuff } public class Stage { public Stage(string stageName) { StageName = stageName; } public readonly string StageName; public override bool Equals(object o) { var other = o as Stage; return other?.StageName == StageName; } public override int GetHashCode() => StageName?.GetHashCode() ?? 0; public override string ToString() => StageName; }
}

Demo:

Output:
Output for MudSelect using ValueChanged event

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like