asp.net-coreblazorblazor-webassembly.net-9.0

<input type="radio"> not binding with @bind in Blazor WASM in .NET 9


I'm try to bind radio buttons using @bind in Blazor wasm. But not able to make successful attempt and also not able to find any docs for this.

I searched in this doc link - https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-9.0

Code:

<div class="control flex flex-col">
    <label class="radio">
        <input type="radio" name="stock" @bind="Filter.InStock" checked="@(Filter.InStock.HasValue && Filter.InStock.Value)" @bind:after="LoadData" />
        In Stock
    </label>
    <label class="radio">
        <input type="radio" name="stock" @bind="Filter.OutOfStock" checked="@(Filter.OutOfStock.HasValue && Filter.OutOfStock.Value)" @bind:after="LoadData" />
        Out of Stock
    </label>
</div>

@code {
  public class StockFilter 
  {
      public bool? InStock { get; set; }
      public bool? OutOfStock { get; set; }
  }

  public StockFilter Filter = new();

  public void LoadData()
  {
      Console.WriteLine("In" + Filter.InStock);
      Console.WriteLine("Out" + Filter.OutOfStock);
      // make API call
  }
}

Console log:

enter image description here

Please can you assist me or point to correct docs link?


Solution

  • Demo page below.

    I've simplified the model and manually set the value using checked attribute and onchange event.

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <div class="control flex flex-col">
        <label class="radio">
            <input type="radio" name="stock" checked="@(this.InStock)" @onchange="() => SetInStock(true)" />
            In Stock
        </label>
        <label class="radio">
            <input type="radio" name="stock" checked="@(!this.InStock)" @onchange="() => SetInStock(false)" />
            Out of Stock
        </label>
    </div>
    
    @code {
        public bool InStock { get; set; }
    
        public Task SetInStock(bool value)
        {
            this.InStock = value;
            // make API call
            // likely to be async so made the method Task based
            return Task.CompletedTask;
        }
    }