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

Blazor中如何获取下拉选择框选中项的索引?

获取Blazor下拉框选中项的索引

下面提供两种实用方法来获取选中选项的索引:

方法一:基于数据绑定(推荐,符合Blazor思想)

通过将下拉框与数据集合绑定,直接通过选中值匹配索引,无需操作DOM:

@code {
    private string test = "105";
    private List<OptionItem> Options = new List<OptionItem>
    {
        new OptionItem { Value = "105", Text = "105" },
        new OptionItem { Value = "107", Text = "107" }
    };

    private int SelectedIndex => Options.FindIndex(o => o.Value == test);

    public class OptionItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
    }
}

<div>
    <select @bind="test">
        @foreach (var option in Options)
        {
            <option value="@option.Value">@option.Text</option>
        }
    </select>
</div>
<p>选中值:@test</p>
<p>选中索引:@SelectedIndex</p>

说明:定义选项集合后,通过FindIndex方法根据选中值匹配对应索引,这种方式更易维护,尤其适用于选项动态变化的场景。

方法二:通过DOM元素获取索引

如果需要直接操作DOM获取选中索引,可使用ElementRef结合JS互操作实现:

@inject IJSRuntime JSRuntime

<div>
    <select @ref="selectElement" @oninput="HandleInput">
        <option value="105" selected>105</option>
        <option value="107">107</option>
    </select>
</div>
<p>选中值:@test</p>
<p>选中索引:@selectedIndex</p>

@code {
    private string test;
    private int selectedIndex;
    private ElementRef selectElement;

    private async Task HandleInput(ChangeEventArgs e)
    {
        test = e.Value.ToString();
        // 通过JS获取select元素的selectedIndex属性
        selectedIndex = await JSRuntime.InvokeAsync<int>("getSelectedIndex", selectElement);
    }
}

<!-- 在wwwroot/index.html的<script>标签中添加以下函数 -->
<script>
    function getSelectedIndex(element) {
        return element.selectedIndex;
    }
</script>

说明:通过@ref获取下拉框的DOM引用,再借助JS互操作读取原生的selectedIndex属性,直接拿到选中项的索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:08:31