Search code examples
radio-buttonblazorparent-childblazor-webassemblytwo-way-binding

How to do two-way binding on a radio button Blazor child component


I'm trying to create a radio button component in Blazor that has two way data binding but I can't seem to get the value (testNumber) on the parent to change. I am new to Blazor and C#, so any help would be greatly appreciated. Thanks

ChildComp.razor

<div>
    <label for="radio1">1</label>
    <input 
        id="radio1"
        type="radio"
        value="1"
        name="test"
        checked="@(_selectedGroup == 1)"
        @onclick="@(() => _selectedGroup = 1)"/>

    <label for="radio2">2</label>
    <input
        id="radio2"
        type="radio"
        value="2"
        name="test"
        checked="@(_selectedGroup == 2)"
        @onclick="@(() => _selectedGroup = 2)"/>

</div>

@code {

    private int _selectedGroup = 0;

    [Parameter]
    public int BindingValue
    {
        get => _selectedGroup;
        set
        {
            if (_selectedGroup == value ) 
            {
                return;
            }
            else
            {
                _selectedGroup = value;
            }
            BindingValueChanged.InvokeAsync(value);
        }
    }

    [Parameter]
    public EventCallback<int> BindingValueChanged { get; set; }   
}

ParentComp.razor

<div>
    <ChildComp @bind-BindingValue="testNumber" />
    <h5>@testNumber</h5> 
</div>

@code {

    int testNumber = 0;
}

Solution

  • As you probably noticed bind does not work with radio buttons. On GitHub you can see the discussion about it here. It's sad that Blazor doesn't support these simple features...

    I had the same problem and came across this solution:

    @code {
        public int EditionCode = 1;
    
        // "Edition" class has "int Code" and "string Text" properties.
        public Edition[] Editions = new [] {
          new Edition { Code = 1, Text = "Home" },
          new Edition { Code = 2, Text = "Pro" },
          new Edition { Code = 3, Text = "Enterprise" },
        };
    }
    
    @foreach (var edition in this.Editions)
    {
    <label>
      <input type="radio" 
             name="edition"
             checked="@(EditionCode == edition.Code)"
             onchange="@(() => EditionCode = edition.Code)"/>
             @edition.Text
    </label>
    }
    

    If this solution doesn't solve your needs, then have a look here (a bit more complex).