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

2

5

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?

Conjunct answered 2/6, 2020 at 13:42 Comment(0)
L
16

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

Lainelainey answered 2/6, 2020 at 15:6 Comment(2)
That worked out for me! Thank you for your help. :)Conjunct
You're welcome... The way to thank folks in stackoverflow is to accept their answer by clicking on the dim check mark to the left of the answer, as well as up voting the answer by clicking on the dimmed up-arrow to the left of the answer. Good day...Lainelainey
L
1

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>
Lille answered 6/9, 2020 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.