Kendo Grid - Passing DataSourceRequest from your own javascript

If you want to call a controller action that is using the DataSourceRequest and you are calling from your own javascript function.
Example of this is serverside export of excel data. The built in excel export couldn't handle the large data so I required a way of exporting all the data not just the data in the viewed grid page. I also want to use the filtering, grouping, sorting the user had set so this information was required to be sent to the server by me rather than the grid.

So where do you get the data?

The grid has all its sorts and filters on the dataSource but to get it in a format for sending then there is a parameterMap function available.

var grid = $("#kgridA").data("kendoGrid");  
var parameterMap = grid.dataSource.transport.parameterMap;  
var data = parameterMap({ sort: grid.dataSource.sort(), filter: grid.dataSource.filter(), group: grid.dataSource.group() });  

This contains all the details for the DataSourceResult apart from paging. You would need to add that if required. I didn't want it.

You can use the data straight off and send it with a jquery ajax

$.ajax({
        url: "/controller/action",
        data: data,
        type: "POST",
        ...etc...

with the controller something like

public FileResult ExportAllExcelData([DataSourceRequest]DataSourceRequest request) {  

Now ajax isn't much use if want to transfer files as I wanted to do so if you dont want to use ajax or have another need to use a GET and not a POST then

        var getparam = "sort="
        if (data.sort !== "") {
            getparam += data.sort;
        } else {
            getparam += "~";
        }
        getparam += "&filter="
        if (data.filter !== "") {
            getparam += data.filter;
        } else {
            getparam += "~";
        }
        getparam += "&group="
        if (data.filter !== "") {
            getparam += data.group;
        } else {
            getparam += "~";
        }

        window.location.href = "/controller/ExportAllExcelData?" + getparam;        

Above referring to version
Telerik Kendo UI Professional Q1 2015
Telerik UI for ASP.NET MVC Q1 2015


comments powered by Disqus