This is a migrated thread and some comments may be shown as answers.

[Solved] Exporting using custom commands

0 Answers 37 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Ryan
Top achievements
Rank 1
Ryan asked on 21 Feb 2011, 11:34 AM
Hi,

I enhanced the custom command example posted here: http://demos.telerik.com/aspnet-mvc/grid/customcommand

I found that if you want multiple export types, such as CSV and Excel, then the example wasn't general enough.  So I've enhanced it below to support multiple export custom command buttons.

First the view code with two custom commands;

.ToolBar(commands => {
            commands.Custom().Text("Export to CSV").HtmlAttributes(new { @class = "exportButton" })
            .Action("ExportPayments", "Payments", new
            {
                currency = Model.Currency.DisplayName,
                page = 1,
                orderBy = "~",
                filter = "~"
            });
            commands.Custom().Text("Export to Excel").HtmlAttributes(new { @class = "exportButton" })
            .Action("ExportPaymentsExcel", "Payments", new
            {
                currency = Model.Currency.DisplayName,
                page = 1,
                orderBy = "~",
                filter = "~"
            });
        })

Notice that we set the class on them to be 'exportButton' and that they refer to different actions.

Now the Javascript that updates the url pointed to by the buttons;

function updateExportLink(that) {
    var grid = $(that).data('tGrid');
 
    // Get the export link as jQuery object
    var $exportLinks = $(that).find('.exportButton');
 
    // Get its 'href' attribute - the URL where it would navigate to
    var href = $exportLinks.attr('href');
 
    // Get just the query string
    var query = href.split('?')[1];
 
    // Update the 'page' parameter with the grid's current page
    query = query.replace(/page=([^&]*)/, 'page=' + grid.currentPage);
 
    // Update the 'orderBy' parameter with the grids' current sort state
    query = query.replace(/orderBy=([^&]*)/, 'orderBy=' + (grid.orderBy || '~'));
 
    // Update the 'filter' parameter with the grids' current filtering state
    query = query.replace(/filter=(.*)/, 'filter=' + (grid.filterBy || '~'));
 
    // Update the 'href' attribute
    $exportLinks.each(function () {
        path = $(this).attr('href').split('?')[0];
        $(this).attr('href', path + "?" + query);
    });
}

Hope this helps someone in the future.

Ryan.
Tags
Grid
Asked by
Ryan
Top achievements
Rank 1
Share this question
or