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

基于C#(ASP.NET Core)实现Data Grid单元格模板遇类型错误问题

DevExtreme DataGrid单元格模板访问强类型属性报错解决方法

问题描述

使用DevExtreme ASP.NET MVC DataGrid绑定List<SupportTicketVM>数据源时,在单元格模板中尝试访问当前行对象的SupportTicketPrefix属性,触发如下编译错误:

'object' does not contain a definition for 'SupportTicketPrefix' and no accessible extension method 'SupportTicketPrefix' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

解决方案

方法1:显式转换item类型

在单元格模板内将item强制转换为SupportTicketVM类型,让编译器识别属性:

@(Html.DevExtreme().DataGrid<SupportTicketVM>()
    .ID("supportTicketDataGrid")
    .DataSource(deviceSupportTickets)
    .Columns(columns =>
    {
        columns.AddFor(m => m.SupportTicketPrefix).Caption("Ticket#").CellTemplate(@<text>
            @{
                var currentTicket = item as SupportTicketVM;
            }
            <a href="dummy_link@currentTicket.SupportTicketPrefix">@currentTicket.SupportTicketPrefix</a>
        </text>);
        // 其他列省略
    })
    // 其他配置省略
)

方法2:使用强类型CellTemplate重载

利用DevExtreme提供的强类型模板方法,直接获取类型化的行数据:

@(Html.DevExtreme().DataGrid<SupportTicketVM>()
    .ID("supportTicketDataGrid")
    .DataSource(deviceSupportTickets)
    .Columns(columns =>
    {
        columns.AddFor(m => m.SupportTicketPrefix)
            .Caption("Ticket#")
            .CellTemplate((container, options) =>
            {
                var currentTicket = options.Data as SupportTicketVM;
                container.Append("<a href='dummy_link" + currentTicket.SupportTicketPrefix + "'>" + currentTicket.SupportTicketPrefix + "</a>");
            });
        // 其他列省略
    })
    // 其他配置省略
)

原因说明

默认情况下,单元格模板中的item变量是object类型,编译器无法推断其具体类型,因此无法直接访问SupportTicketPrefix属性。通过显式类型转换或使用强类型模板方法,让编译器明确变量类型即可解决该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:22:49