You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Blazor Input Radio Group绑定失效问题求助

问题原因及解决方案

核心问题:类型不匹配

你的Model.Selected是int类型,但InputRadio的Value属性设置的是字符串("1"、"2"),Blazor无法自动完成字符串到整数的类型转换,导致选中状态无法同步到绑定属性。

其他可优化点

  • InputRadioGroup不需要设置Name属性,它会通过@bind-Value自动关联所属的单选框组,额外设置Name可能引发冲突。
  • OnInitialized中重复初始化model属于冗余操作,可移除。

修改后的完整代码

@page "/"
<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
  <title>Example</title>
</head>
<body>
  <div class="container">
    <div class="jumbotron">
      <EditForm EditContext="editContext" FormName="uniqueForm">
        <fieldset class="row mb-3">
          <legend class="col-form-label col-sm-2 pt-0">Checksum type:</legend>
          <div class="col-sm-10">
            <InputRadioGroup @bind-Value="model.Selected">
              <div class="form-check">
                <InputRadio Value="1" class="form-check-input" />
                <label class="form-check-label">
                  One
                </label>
              </div>
              <div class="form-check">
                <InputRadio Value="2" class="form-check-input" />
                <label class="form-check-label">
                  Two
                </label>
              </div>
            </InputRadioGroup>
          </div>
        </fieldset>
      </EditForm>
      <div>
        Selected: @model.Selected
      </div>
    </div>
  </div>
</body>
</html>

@code
{
  private Model model = new();
  private EditContext? editContext;

  protected override void OnInitialized()
  {
    editContext = new EditContext(model);
  }

  public class Model
  {
    public int Selected { get; set; }
  }
}

验证说明

修改后,InputRadio的Value直接使用整数(Blazor会自动处理类型匹配),移除了多余的Name属性,此时点击单选按钮,页面底部的Selected值会实时更新为选中的数字。

内容的提问来源于stack exchange,提问作者M2evorah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.05 04:12:32