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

Blazor 8中InputSelect下拉框双向联动问题求助(无需JSRuntime)

Blazor 8 双向联动下拉框解决方案

问题根源

  1. 下拉框值绑定不匹配:原代码中年龄下拉框的option值绑定了pers.Name,但绑定字段是selectedAge;姓名下拉框的option值绑定了pers.Age,绑定字段是selectedName,导致选中值无法匹配对应选项。
  2. 缺少联动逻辑:未在选中值变化时同步更新另一个下拉框的选中状态。

修正代码

@inject PersonContext DB

<div class="mb-3">
    <label for="pAge" class="form-label">Age:</label>
    <InputSelect @bind-Value="selectedAge">                          
        <option value="">select an age...</option>
        @foreach (var pers in DB.Persons)
        {
            <option value="@pers.Age.ToString()">
                @pers.Age
            </option>
        }
    </InputSelect>
</div>  
<div class="mb-3">
    <label for="pName" class="form-label">name:</label> 
    <InputSelect @bind-Value="selectedName">
        <option value="">select a name...</option>
        @foreach (var pers in DB.Persons)
        {
            <option value="@pers.Name">
                @pers.Name
            </option>
        }
    </InputSelect>
</div>  

@code {
    private string? _selectedName;
    private string? _selectedAge;

    public string? selectedName
    {
        get => _selectedName;
        set
        {
            if (_selectedName != value)
            {
                _selectedName = value;
                // 联动更新年龄:根据选中的姓名找到对应Person的年龄
                if (!string.IsNullOrEmpty(value))
                {
                    var person = DB.Persons.FirstOrDefault(p => p.Name == value);
                    if (person != null)
                    {
                        _selectedAge = person.Age.ToString();
                    }
                }
                else
                {
                    _selectedAge = string.Empty;
                }
            }
        }
    }

    public string? selectedAge
    {
        get => _selectedAge;
        set
        {
            if (_selectedAge != value)
            {
                _selectedAge = value;
                // 联动更新姓名:根据选中的年龄找到对应Person的姓名
                if (!string.IsNullOrEmpty(value) && int.TryParse(value, out int age))
                {
                    var person = DB.Persons.FirstOrDefault(p => p.Age == age);
                    if (person != null)
                    {
                        _selectedName = person.Name;
                    }
                }
                else
                {
                    _selectedName = string.Empty;
                }
            }
        }
    }
}

关键说明

  • 修正值绑定:年龄下拉框的option值改为pers.Age.ToString()(适配selectedAge的string类型),姓名下拉框的option值改为pers.Name,确保绑定值与选项值完全匹配。
  • 属性setter联动:在两个选中字段的setter中添加逻辑,当其中一个值变化时,从Person列表中匹配对应项,自动更新另一个字段的值,触发UI同步选中状态。
  • 空值处理:选择默认空选项时,同步清空另一个下拉框的选中值,保持状态一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:52:46