Radio button binding is not happening in blazor. As per the documentation it is suggested to use InputRadio tag but this tag doesn't work in blazor and shows binding issue. Any suggestions on how to bind a radio button
Of course it is, it is described here:
@using System.Globalization
@typeparam TValue
@inherits InputBase<TValue>
<input @attributes="AdditionalAttributes" type="radio" value="@SelectedValue"
checked="@(SelectedValue.Equals(Value))" @onchange="OnChange" />
@code {
[Parameter]
public TValue SelectedValue { get; set; }
private void OnChange(ChangeEventArgs args)
{
CurrentValueAsString = args.Value.ToString();
}
protected override bool TryParseValueFromString(string value,
out TValue result, out string errorMessage)
{
var success = BindConverter.TryConvertTo<TValue>(
value, CultureInfo.CurrentCulture, out var parsedValue);
if (success)
{
result = parsedValue;
errorMessage = null;
return true;
}
else
{
result = default;
errorMessage = $"{FieldIdentifier.FieldName} field isn't valid.";
return false;
}
}
}
Usage
@page "/RadioButtonExample"
@using System.ComponentModel.DataAnnotations
<h1>Radio Button Group Test</h1>
<EditForm Model="@model" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
@for (int i = 1; i <= 5; i++)
{
<label>
<InputRadio name="rate" SelectedValue="i" @bind-Value="model.Rating" />
@i
</label>
}
<button type="submit">Submit</button>
</EditForm>
<p>You chose: @model.Rating</p>
@code {
private Model model = new Model();
private void HandleValidSubmit()
{
...
}
public class Model
{
[Range(1, 5)]
public int Rating { get; set; }
}
}
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