I am trying to bind the value of a radio button in .NET 5.0 Blazor WASM Hosted project. The code is simple but it is not working. The value of anyValue remains "false" after submitting the form.
Parent Component
<EditForm Model="model" OnValidSubmit="OnSubmitForm">
<RadioButton Name="TestRadio" Text="Choose value" Value="@anyValue" />
</EditForm>
@code {
string anyValue = "false";
......................
private async Task OnSubmitForm()
{
model.TestRadio = Convert.ToBoolean(anyValue);
}
......................
}
RadioButton Component
<div >
<label>
@Text
</label>
<div>
<InputRadioGroup Name="@Name" @bind-Value="@Value" >
<InputRadio Name="@Name" Value="@trueVal" />Yes<br>
<InputRadio Name="@Name" Value="@falseVal" />No<br>
</InputRadioGroup>
</div>
</div>
@code {
string trueVal = "true";
string falseVal = "false";
[Parameter]
public string Text { get; set; }
[Parameter]
public string Name { get; set; }
[Parameter]
public string Value { get; set; }
}
What am I doing wrong and how to fix it? I do not like the code myself but Blazor just has a strange way of handling these...
CodePudding user response:
This is the right way:
@page "/"
<div>
<h4> vehicle Selected - @vehicle.Name </h4>
<EditForm Model="vehicle">
<InputRadioGroup @bind-Value="vehicle.Name">
@foreach (var option in rdOptions)
{
<InputRadio Value="option" /> @option <br />
}
</InputRadioGroup>
</EditForm>
</div>
@code {
public class Vehicle
{
public string Name { get; set; }
}
Vehicle vehicle = new Vehicle()
{
Name = "auto" // default value
};
List<string> rdOptions = new List<string> { "car", "bus", "auto" };
}
You can put the model on another layer
CodePudding user response:
Try @bind instead of @value - ... Sorry, this is a mistake, never mind. Ignore my post because I cannot delete it
