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;
}
CodePudding user response:
You can use ValueChanged
event callback which is fired when the Value property changes.
Implementation:
<MudSelect T="Stage"
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;}
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;
}
}