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

MudBlazor MudSelect绑定Int类型值时类型转换错误求助

解决MudSelect绑定int类型CategoryId的问题

错误根源

你遇到的类型转换错误,核心是MudSelect的泛型类型与绑定值类型不匹配,或是内部MudSelectItem的Value类型和外层MudSelect的泛型类型不一致,导致框架尝试在string和int之间强制转换。


正确示例(两种写法)

1. 手动遍历生成MudSelectItem

先定义基础模型:

// 交易模型
public class TransactionModel
{
    public int CategoryId { get; set; }
    // 其他业务属性...
}

// 分类模型
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Razor页面代码:

<MudSelect T="int" @bind-Value="NewTransaction.CategoryId" Label="选择分类">
    @foreach (var category in Categories)
    {
        <!-- 注意MudSelectItem的T必须和外层MudSelect一致,Value是int类型的分类ID -->
        <MudSelectItem T="int" Value="category.Id">@category.Name</MudSelectItem>
    }
</MudSelect>

@code {
    // 初始化新交易对象
    public TransactionModel NewTransaction { get; set; } = new TransactionModel();
    // 模拟分类数据
    public List<Category> Categories { get; set; } = new List<Category>
    {
        new Category { Id = 1, Name = "餐饮消费" },
        new Category { Id = 2, Name = "交通出行" },
        new Category { Id = 3, Name = "购物支出" }
    };
}

2. 使用Items属性批量绑定

这种写法更简洁,适合直接绑定集合数据:

<MudSelect T="int" 
           @bind-Value="NewTransaction.CategoryId" 
           Items="Categories" 
           ItemText="@(item => item.Name)"  <!-- 指定显示的文本字段 -->
           ItemValue="@(item => item.Id)"   <!-- 指定绑定的int类型字段 -->
           Label="选择分类">
</MudSelect>

@code {
    public TransactionModel NewTransaction { get; set; } = new TransactionModel();
    public List<Category> Categories { get; set; } = new List<Category>
    {
        new Category { Id = 1, Name = "餐饮消费" },
        new Category { Id = 2, Name = "交通出行" },
        new Category { Id = 3, Name = "购物支出" }
    };
}

关键注意事项

  • 必须保证MudSelect的T类型和绑定的CategoryId类型完全一致(这里是int)
  • 手动添加MudSelectItem时,其T类型必须与外层MudSelect的T一致,且Value必须是int类型
  • 使用Items属性时,通过ItemValue明确指定要绑定的int类型字段,避免框架自动推断错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:49:55