gpt4 book ai didi

c# - 如何在 Blazor 中绑定(bind)单选按钮?

转载 作者:行者123 更新时间:2023-12-04 02:30:44 25 4
gpt4 key购买 nike

blazor 中没有发生单选按钮绑定(bind)。根据文档,建议使用 InputRadio 标签,但此标签在 blazor 中不起作用并显示绑定(bind)问题。关于如何绑定(bind)单选按钮的任何建议

最佳答案

当然是,这里有描述:https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1#radio-buttons

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

关于c# - 如何在 Blazor 中绑定(bind)单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64365100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com