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

如何在.NET 8 Blazor Server中正确处理MudBlazor多选下拉框

解决方案

1. 调整绑定类型与组件参数

将CurrentValue的类型改为List<int>,直接存储选中部门的数值Key列表,继承自InputBase<List<int>>:

// 替换原CurrentValue定义
[Parameter]
public List<int> CurrentValue { get; set; } = new List<int>();

// 保持Departments参数不变
[Parameter]
public List<SelectListItem> Departments { get; set; } = new List<SelectListItem>();

2. 修改MudSelect与MudSelectItem配置

把MudSelect的泛型类型T设为int,绑定到CurrentValue;同时将MudSelectItem的Value转换为数值类型,确保与绑定值类型匹配:

<MudSelect T="int" @bind-Value="CurrentValue" MultiSelection="true" 
           MultiSelectionTextFunc="@GetMultiSelectionText">
    @foreach (var item in Departments)
    {
        <MudSelectItem T="int" Value="@int.Parse(item.Value)">@item.Text</MudSelectItem>
    }
</MudSelect>

3. 适配多选显示文本函数

调整GetMultiSelectionText的参数为List<int>,通过数值Key匹配对应的部门名称,生成显示文本:

private string GetMultiSelectionText(List<int> selectedKeys)
{
    var selectedTexts = selectedKeys
        .Select(key => Departments.FirstOrDefault(x => int.Parse(x.Value) == key)?.Text)
        .Where(text => !string.IsNullOrEmpty(text));

    return string.Join("; ", selectedTexts);
}

额外说明

  • 若部门Key超出int范围,可替换为long类型,同步调整泛型与转换逻辑。
  • 如需将Key列表转为拼接字符串存储,提交时执行:string joinedKeys = string.Join(",", CurrentValue);;读取时拆分转回List<int>即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 00:00:01