Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind radio buttons to a property which is an enum?

I'm working on radio buttons using Blazor. There have to be 2 radio buttons for the salutation of a person. But the salutation of the person is already clear. So for example if it's a man, I need the man radio button to be checked when I load the page. The problem is that I can't use @bind-Value for a radio button. Can anyone help me?

like image 926
Lumberjack Avatar asked Jun 02 '20 13:06

Lumberjack


Video Answer


2 Answers

Please model your code after this sample:

@foreach (var choice in new[] { Choices.Red, Choices.Green, Choices.Blue })
{
    <label>
        <input name="yourColor" type="radio"
               value="@choice"
               checked="@(currentChoice == choice)"
               @onchange="@(() => { currentChoice = choice; })">
        @choice.ToString()
    </label>
}

<p>You chose: @currentChoice</p>

@code {
    enum Choices { Red, Green, Blue };
    Choices currentChoice = Choices.Red;
}

Hope this helps...

Source: https://github.com/dotnet/aspnetcore/issues/5579#issuecomment-548061223

like image 181
enet Avatar answered Oct 17 '22 23:10

enet


As you are specifically asking for a binding solution:

There is no native Blazor binding solution so far... But the project Blazorise offers a pure binding solution for this problem:.

@code{

    enum MyEnum
    {
        A = 0,
        B = 1,
        C = 2,
        D = 3
    }
    
    MyEnum checkedValue { get; set; } = MyEnum.B;

}

The code in a .razor file:

<p>Current count: @(checkedValue.ToString())</p>

<RadioGroup TValue="MyEnum" Name="group1" @bind-CheckedValue="@checkedValue">
    @foreach (var val in Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>()) {
        <Radio TValue="MyEnum" Value="@val">@(val.ToString())</Radio>
    }
</RadioGroup>
like image 23
ndsvw Avatar answered Oct 17 '22 22:10

ndsvw