如何用Razor语法在TabStrip内的Kendo UI Grid添加自定义工具栏按钮?
解决TabStrip内Grid自定义工具栏按钮的嵌套@问题
针对你遇到的Kendo UI Razor语法中TabStrip嵌套Grid时无法使用自定义工具栏按钮的问题,这里提供几种实用的解决思路:
方法一:使用局部视图拆分代码
把带自定义工具栏的Grid单独抽成局部视图,彻底避免嵌套@的问题:
- 创建局部视图(比如
_GridWithCustomToolbar.cshtml),在里面编写完整的Grid配置,包括自定义工具栏:
@model IEnumerable<YourDataModel> @(Html.Kendo().Grid<YourDataModel>() .Name("DataGrid") .ToolBar(tools => { tools.Template(@<text> <button class="k-button k-primary" onclick="handleCustomClick()">自定义操作按钮</button> </text>); }) .Columns(cols => { // 配置你的列 cols.Bound(m => m.Id); cols.Bound(m => m.Name); }) .DataSource(ds => ds.Ajax() .Read(read => read.Action("GetData", "Home")) ) )
- 在TabStrip的Content中直接调用这个局部视图:
@(Html.Kendo().TabStrip() .Items(items => { items.Add().Text("数据页签") .Content(Html.Partial("_GridWithCustomToolbar").ToHtmlString()); }) )
方法二:用字符串模板替代@
把工具栏的HTML直接写成字符串,不用@标签,就能在TabStrip的@内正常使用:
@(Html.Kendo().TabStrip() .Items(items => { items.Add().Text("数据页签").Content(@<text> @(Html.Kendo().Grid<YourDataModel>() .Name("DataGrid") .ToolBar(tools => { // 直接传入HTML字符串作为模板 tools.Template("<button class='k-button k-primary' onclick='handleCustomClick()'>自定义操作按钮</button>"); }) .Columns(cols => { cols.Bound(m => m.Id); cols.Bound(m => m.Name); }) .DataSource(ds => ds.Ajax().Read(r => r.Action("GetData", "Home"))) ) </text>); }) )
方法三:使用@helper封装工具栏模板
通过Razor的@helper定义工具栏内容,再转成HTML字符串传入Grid的ToolBar:
@helper CustomToolbarTemplate() { <button class="k-button k-primary" onclick="handleCustomClick()">自定义操作按钮</button> } @(Html.Kendo().TabStrip() .Items(items => { items.Add().Text("数据页签").Content(@<text> @(Html.Kendo().Grid<YourDataModel>() .Name("DataGrid") .ToolBar(tools => { tools.Template(CustomToolbarTemplate().ToHtmlString()); }) .Columns(cols => { cols.Bound(m => m.Id); cols.Bound(m => m.Name); }) .DataSource(ds => ds.Ajax().Read(r => r.Action("GetData", "Home"))) ) </text>); }) )
补充说明:为什么tools.Custom和ClientTemplate没生效
tools.Custom:这个方法是用来添加带预定义行为的自定义工具,需要指定Name、Url等属性,更适合跳转类的按钮,不是用来渲染任意HTML模板的。tools.ClientTemplate:仅适用于客户端绑定的Grid(即通过客户端数据源配置的场景),如果你的Grid是服务器端绑定,这个模板不会被渲染。
内容的提问来源于stack exchange,提问作者Belgabad
相关产品推荐
相关产品推荐

