【问题标题】:How to bind Radio Buttons In Blazor?如何在 Blazor 中绑定单选按钮?
【发布时间】:2021-01-29 13:20:18
【问题描述】:

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

【问题讨论】:

    标签: c# binding radio-button blazor


    【解决方案1】:

    当然是,这里有描述: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; }
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2011-08-21
    • 2014-12-15
    相关资源
    最近更新 更多