我尝试在Kendo Grid的工具栏上创建自定义命令按钮。代码就像

Html.Kendo().Grid...
.ToolBar(commands => commands.Custom().Text("Export").Action("ExportAthletePageToExcel", "ExportExcelButton", new { selectedSportId = Model.CurrentSport, yearId = Model.CurrentYear }))
...
Controller is like,
public ActionResult ExportAthletePageToExcel(DataSourceRequest request, string selectedSportId, string yearId)
...


它适用于selectedSportId和yearId之类的参数,除非请求没有关于网格的正确信息(过滤器,排序,页面等)。我想知道是什么问题。

谢谢。

最佳答案

我间接偶然发现了我喜欢的解决方案。 Telerik发布了一个演示,用于将网格内容导出到Excel。他们使用自定义命令,并使用网格的OnDataBound事件在客户端的javascript中设置DataSourceRequest参数。我在这里为您整理了相关的内容...


在Action的路由值中包含四个DataSourceRequest参数,但要使用占位符波浪号,这些参数将在步骤2中替换:

.ToolBar(commands => commands.Custom().Text("Export").Action("ExportAthletePageToExcel", "ExportExcelButton", new { page = "~", pageSize = "~", filter = "~", sort = "~", selectedSportId = Model.CurrentSport, yearId = Model.CurrentYear }))

在DataBound事件中包含对javascript函数的调用:

.Events(ev => ev.DataBound("onDataBound"))

然后将以下脚本添加到页面:

function onDataBound(e) {
var grid = this;

// ask the parameterMap to create the request object for you
var requestObject = (new kendo.data.transports["aspnetmvc-server"]({ prefix: "" }))
.options.parameterMap({
    page: grid.dataSource.page(),
    sort: grid.dataSource.sort(),
    filter: grid.dataSource.filter()
});

// Get the export link as jQuery object
var $exportLink = grid.element.find('.export');
// Get its 'href' attribute - the URL where it would navigate to
var href = $exportLink.attr('href');
// Update the 'page' parameter with the grid's current page
href = href.replace(/page=([^&]*)/, 'page=' + requestObject.page || '~');
// Update the 'sort' parameter with the grid's current sort descriptor
href = href.replace(/sort=([^&]*)/, 'sort=' + requestObject.sort || '~');
// Update the 'pageSize' parameter with the grid's current pageSize
href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + grid.dataSource._pageSize);
//update filter descriptor with the filters applied
href = href.replace(/filter=([^&]*)/, 'filter=' + (requestObject.filter || '~'));
// Update the 'href' attribute
$exportLink.attr('href', href);


}
现在,在控制器方法中,您将可以访问带有当前状态填充的所有相关参数的DataSourceRequest。还要注意,您在方法的request参数中缺少属性[DataSourceRequest],因此它应如下所示:

public ActionResult ExportAthletePageToExcel([DataSourceRequest]DataSourceRequest request, string selectedSportId, string yearId)

07-24 21:28