blazor中未发生单选按钮绑定。根据文档,建议使用InputRadio标记,但此标记在blazor中不起作用,并且显示了绑定问题。关于如何绑定单选按钮的任何建议
当然是这样,这里有描述:
@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;
}
}
}
使用
@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; }
}
}
以下代码适用于我的
<input type="radio" checked="@(User.Gender == GenderEnum.Male)"
name="Gender" @onchange="@(() => User.Gender = GenderEnum.Male)" />
<label>Male</label>
<input type="radio" checked="@(User.Gender == GenderEnum.Female)"
name="Gender" @onchange="@(() => User.Gender = GenderEnum.Female)" />
<label>Female</label>
<input type="radio" checked="@(User.Gender == GenderEnum.Other)"
name="Gender" @onchange="@(() => User.Gender = GenderEnum.Other)" />
<label>Other</label>
我们也可以有一个从@onchange
调用的函数,比如@onchange="@UpdateGender"