无法在 Blazor WASM 应用程序中使用 InputRadio 和 InputRadioGroup 绑定单选按钮

Unable to bind radio button using InputRadio and InputRadioGroup in Blazor WASM app

我正在尝试在 .NET 5.0 Blazor WASM 托管项目中绑定单选按钮的值。代码很简单,但不起作用。 anyValue 的值在提交表单后仍然为“false”。

父组件

<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);
       }

       ......................
   }

单选按钮组件

<div class="form-group">
    <label>
        @Text
    </label>
    <div>
        <InputRadioGroup Name="@Name" @bind-Value="@Value" class="form-control col-sm-4">
            <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; }
}

我做错了什么以及如何解决?我自己不喜欢这些代码,但 Blazor 处理这些代码的方式很奇怪...

这是正确的方法:

@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" };




   }

您可以将模型放在另一层

组件:

<div class="form-group">
    <label>
        @Text
    </label>
    <div>
        <div>
              <input type="radio"  name="@Name"  @onchange=@(()=>OnValueChange(trueVal)) checked="@(Value==@trueVal)">
              <label >@trueVal</label>
            </div>

            <div>
              <input type="radio" name="@Name"  @onchange=@(()=>OnValueChange(falseVal)) checked="@(Value==@falseVal)">
              <label>@falseVal</label>
            </div>
    </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; }

    [Parameter]
    public EventCallback<string> ValueChanged { get; set; }

    private void OnValueChange(string val){
        Value=val;
        ValueChanged.InvokeAsync(val);
    }
}

在父剃须刀页面中使用:

<RadioButton Name="TestRadio" Text="Choose value" @bind-Value="model.TestRadio" />