Skip to main content
 首页 » 编程设计

c#之为什么 DatasourceRequest 没有传递到 Kendo Grid 中工具栏的自定义命令

2024年02月06日16daizhj

我尝试在 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 参数。我在这里为您整理了相关的部分...

  1. 在 Action 的路由值中包含四个 DataSourceRequest 参数,但带有将在第 2 步中替换的占位符波浪号:

    .ToolBar(commands => commands.Custom().Text("Export").Action("ExportAthletePageToExcel", "ExportExcelButton", new { page = "~", pageSize = "~", filter = "~", sort = "~", selectedSportId = Model.CurrentSport, yearId = Model.CurrentYear })) 
    
  2. 在 DataBound 事件中包含对 javascript 函数的调用:

    .Events(ev => ev.DataBound("onDataBound")) 
    
  3. 然后将以下脚本添加到页面:

    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); 
    

  4. 现在,在您的 Controller 方法中,您将可以访问 DataSourceRequest,所有相关参数均填充有当前状态。另请注意,您在方法的请求参数中缺少属性 [DataSourceRequest],因此它应该如下所示:

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