Question

I have Telerik Grid from MVC Extensions and I'm trying to create export to xlsx based on data in grid.

Problem is, that I'm not quite sure how to get information about actual user filters in grid.

Suppose the user filters the grid by applying a filter on Name, like the name starts with "Bu". And furthermore, the user orderd by Age.

The URL will be something like:

?listing-1-page=1&listing-1-orderBy=Age-asc&listing-1-groupBy=~&listing-1-filter=Name~startswith~'Bu'

I can surely parse this like a string and get data what I need. However this parsing will be quite complex and too tied to this specific grid.

Question is,

is there a way to get IQueryable from grid? From what I found, this IQueryable is generated after Action method is executed in OnActionExecuted. My idea is, I add button to grid toolbar which will call ActionMethod

 public FileStreamResult MyExportMethod()

and in this method I "somehow" get the IQueryable from grid.

Thank you,

Was it helpful?

Solution

If it's grid used with server binding, it is not possible to use Client Event OnDataBound showed here: http://demos.telerik.com/aspnet-mvc/razor/grid/customcommand (thanks to ataravati's comment)

However, event OnLoad will be fired.

Solution can look like:

In cshtml:

    t.Custom().HtmlAttributes(new { id = "export" }).
      Text("Export").Action("Export", "Home", new { page = 1, orderBy = "~", filter = "~" });
    .ClientEvents(events => events.OnLoad("OnLoad"))


<script type="text/javascript">
    function OnLoad() {
        var grid = $(this).data('tGrid');

        // Get the export link as jQuery object
        var $exportLink = $('#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=' + grid.currentPage);

        // Update the 'orderBy' parameter with the grids' current sort state
        href = href.replace(/orderBy=([^&]*)/, 'orderBy=' + (grid.orderBy || '~'));

        // Update the 'filter' parameter with the grids' current filtering state
        href = href.replace(/filter=(.*)/, 'filter=' + (grid.filterBy || '~'));

        // Update the 'href' attribute
        $exportLink.attr('href', href);
    }
</script>

In Controler

  public ActionResult Export(int page, string orderBy, string filter)
  {
     IEnumerable orders = GetOrders().AsQueryable().ToGridModel(page, 10, orderBy, string.Empty, filter).Data;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top