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?
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With