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

如何在MudSelect中获取自定义类multiselectitem的选中项列表?

解决MudSelect自定义类多选无法获取选中项的问题

你的代码存在几个关键问题导致无法获取选中项,修复方案如下:

核心问题及修复点

  • 选中项集合未指定泛型:原代码中selectedtestitems是无类型List,无法正确绑定自定义的multiselectitem,需要改为List<multiselectitem>。
  • 未正确渲染MudSelect选项:@foreach循环没有生成对应的选项组件,需要在MudSelect内部添加MudSelectItem。
  • 未启用多选绑定:必须通过@bind-SelectedValues将选中项和集合双向绑定,同时开启MultiSelection="true"启用多选模式。

修复后的完整代码

<MudSelect T="multiselectitem" 
           @bind-SelectedValues="selectedtestitems" 
           MultiSelection="true"
           ToStringFunc="@ToString"
           Label="选择项目">
    @foreach (multiselectitem item in allitems)
    {
        <MudSelectItem Value="item">@item.name</MudSelectItem>
    }
</MudSelect>

<MudButton OnClick="ProcessTheList" Variant="Variant.Filled" Color="Color.Primary">Submit</MudButton>

@code {
private List<multiselectitem> selectedtestitems = new();

private List<multiselectitem> allitems = new() {
    new multiselectitem{id = 1, name = "test 1"},
    new multiselectitem{id = 2, name = "test 2"},
    new multiselectitem{id = 3, name = "test 3"},
    new multiselectitem{id = 4, name = "test 4"},
};

private string ToString(multiselectitem x)
    => x is null ? string.Empty : $"{x.name}";

public class multiselectitem
{
    public int id { get; set; }
    public string name { get; set; }
    public override bool Equals(object o)
    {
        var other = o as multiselectitem;
        return other?.id == id;
    }
    public override int GetHashCode() => id.GetHashCode();
}

public void ProcessTheList()
{
    foreach (var item in selectedtestitems)
    {
        Console.WriteLine(item.name);
    }
}
}

关键修改说明

  1. 泛型集合修正:selectedtestitems改为List<multiselectitem>,确保类型匹配,能正确接收选中的自定义对象。
  2. MudSelect配置:添加MultiSelection="true"开启多选,@bind-SelectedValues绑定选中项集合,ToStringFunc指定选项显示的文本逻辑。
  3. 选项渲染:在MudSelect内部通过MudSelectItem循环生成每个选项,将Value绑定到对应的multiselectitem实例。

这样修改后,点击Submit按钮时,selectedtestitems就能正确获取到所有选中的项,ProcessTheList方法也能正常输出选中项的名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:17:13