如何为ASP.NET MVC Kendo UI Grid实现本地数据层级展开?
实现Kendo UI Grid行展开展示层级本地数据
问题描述
现有绑定AttributeModel列表的Kendo UI Grid,需实现点击行(或展开箭头)时展示该行对应的AttributeValueModel数据(Value和IsDefault属性),所有数据已通过@Model加载完成,无需后端接口请求。
当前Grid代码:
@if (Model.Attributes != null && Model.Attributes.Any()) { @(Html.Kendo().Grid<AttributeModel>() .BindTo(Model.Attributes) .Name("AttributesGrid") .Height(800) .Scrollable() .Columns(columns => { columns.Bound(attribute => attribute.Code).Title("Code"); columns.Bound(attribute => attribute.ProfessionCode).Title("Proffesion code"); }) ) }
模型定义:
public class AttributeModel { public long Id { get; set; } public string Code { get; set; } public string ProfessionCode { get; set; } public List<AttributeValueModel> AttributeValues { get; set; } } public class AttributeValueModel { public long Id { get; set; } [Required] public long AttributeId { get; set; } [Required] public string Value { get; set; } public bool IsDefault { get; set; } }
解决方案
利用Kendo Grid的DetailTemplate(详情模板)实现本地嵌套数据的层级展示,配合Expandable启用展开功能,可选绑定行点击事件实现整行触发展开。
完整实现代码
@if (Model.Attributes != null && Model.Attributes.Any()) { @(Html.Kendo().Grid<AttributeModel>() .BindTo(Model.Attributes) .Name("AttributesGrid") .Height(800) .Scrollable() // 启用行展开箭头 .Expandable(exp => exp.Enabled(true)) // 配置详情模板,渲染子数据表格 .DetailTemplate(@<text> <div style="padding: 10px;"> @(Html.Kendo().Grid<AttributeValueModel>() .Name($"AttributeValuesGrid_{#=Id#}") // 用父行ID生成唯一子Grid名称 .BindTo(item.AttributeValues) // 直接绑定本地嵌套数据 .Columns(columns => { columns.Bound(v => v.Value).Title("Value"); columns.Bound(v => v.IsDefault).Title("Is Default") .ClientTemplate("<input type='checkbox' disabled #= IsDefault ? 'checked' : '' # />"); }) .Scrollable(false) .NoRecords("无属性值数据") ) </div> </text>) .Columns(columns => { columns.Bound(attribute => attribute.Code).Title("Code"); columns.Bound(attribute => attribute.ProfessionCode).Title("Profession code"); // 修正原拼写错误 }) // 可选:绑定行点击事件,实现点击整行展开/收起 .Events(events => events.DataBound("onGridDataBound")) ) } <script> function onGridDataBound() { const grid = $("#AttributesGrid").data("kendoGrid"); grid.tbody.on("click", "tr", function() { grid.expandRow(this); }); } </script>
关键说明
- DetailTemplate:通过
@<text>包裹模板内容,内部创建子Grid,用父行ID生成唯一子Grid名称避免冲突,直接通过item.AttributeValues绑定本地嵌套数据,无需后端请求。 - Expandable:启用后每行首列会显示展开箭头,点击箭头即可切换展开状态。
- 行点击触发:通过
DataBound事件绑定行点击逻辑,调用expandRow方法实现整行点击展开/收起。 - IsDefault可视化:使用
ClientTemplate渲染禁用的复选框,直观展示是否为默认值。
内容的提问来源于stack exchange,提问作者Randy Marsh
相关产品推荐
相关产品推荐

