我正试图在.NET 5.0 Blazor WASM Hosted项目中绑定一个单选按钮的值。代码很简单,但不起作用。CCD_ 1的值保持为"0";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只是有一种奇怪的处理方式。。。
组件:
<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" />
这是正确的方法:
@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" };
}
你可以把模型放在另一层上