0
votes

I'm using a Telerik web component named RadGrid binded with an Asp.Net ObjectDataSource. It allows the binded data to be exported to an Excel/PDF/Word format. The issue is that I havn't been able to trigger a javascript alert when the download of the file is completed. I've tried OnResponseEnd method on Javascript but it does not work.

¿Any suggestions?

This is my codebehind code so far.

protected void bXls_Click(object sender, EventArgs e)
    {
        RadGrid1.MasterTableView.GetColumn("Historico").Visible = false;
        RadGrid1.MasterTableView.GetColumn("TareaIdExport").Visible = true;

        RadGrid1.ExportSettings.IgnorePaging = true;
        RadGrid1.ExportSettings.OpenInNewWindow = false;
        RadGrid1.MasterTableView.ExportToExcel();
    }

and the short version of the component code

<telerik:RadGrid ID="RadGrid1" runat="server"
                    AutoGenerateColumns="False"
                    Culture="es-ES"
                    GroupPanelPosition="Top" DataSourceID="objGrid"
                    OnItemCommand="RadGrid1_ItemCommand"
                    OnItemDataBound="RadGrid1_ItemDataBound"
                    RenderMode="Lightweight"
                    OnPreRender="RadGrid1_PreRender1"
                    AllowFilteringByColumn="True"
                    AllowPaging="True"
                    AllowSorting="True"
                    OnItemCreated="RadGrid1_ItemCreated"
                    PageSize="4"
                    OnGridExporting="RadGrid1_GridExporting"
                    OnPdfExporting="RadGrid1_PdfExporting"> 
</telerik:RadGrid>
1

1 Answers

1
votes

Because a export requires a full postback, ajax cannot be used limiting what is returned from the post. This makes handling the complete event difficult. What you can do is use a cookie which will be returned from the full postback of the export. The following tutorial uses this approach to solve a similar problem of showing an AjaxLoadingPanel during the export.

A summary of the solution is as follows. When the export is finished, server-side a cookie is added to the form. Meanwhile, the client is polling and looking for this cookie. When the client finds the cookie it means the export is completed.

Show loading panel when exporting RadGrid

Here is a working sample of the code adjusted for your scenario:

ASPX:

function gridCommand(sender, args) {
  if (args.get_commandName().startsWith("Export")) {

    //initiate cookie polling
    appendDownloadToken();
  }
}

function appendDownloadToken() {
  window._downloadToken = new Date().getTime() + "";
  //add a form field containing the download token before submit
  $telerik.$("<input type='hidden' id='_downloadToken' name='_downloadToken' value='" + window._downloadToken + "' />").appendTo(document.forms[0]);

  pollDownloadCookie();
}


function pollDownloadCookie() {
  //compare cookie value and initial value
  if (cookie.get("_downloadToken") === window._downloadToken) {
    //erase download token cookie
    cookie.erase("_downloadToken");
    //remove the token value
    delete window._downloadToken;
    //remove the form field
    $telerik.$("#_downloadToken").remove();
    //show alert
    alert('Grid Exported');
  } else {
    setTimeout(pollDownloadCookie, 100);
  }
}

//Helper method to deal with cookies
cookie = {
  get: function(name) {
    var part = document.cookie.split(name + "=")[1];
    return part ? decodeURIComponent(part.split(";")[0]) : null;
  },
  set: function(name, value, days, path, secure) {
    document.cookie = [
      name + "=" + encodeURIComponent(value),
      days ? "expires=" + new Date(new Date().getTime() + (days * 24 * 60 * 60 * 1000)).toUTCString() : "",
      secure ? "secure" : "",
      path ? "path=" + path : "path=/"
    ].join("; ");
  },
  erase: function(name) {
    cookie.set(name, "", -1);
  },
  all: function() {
    var ret = {};
    var arr = document.cookie.split(";");
    for (var i = 0; i < arr.length; i++) {
      if (arr[i]) {
        var pair = arr[i].split("=");
        ret[pair[0]] = decodeURIComponent(pair[1]);
      }
    }
    return ret;
  }
}
<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource" AutoGenerateColumns="false" OnItemCommand="RadGrid1_ItemCommand">
  <ExportSettings ExportOnlyData="True" HideStructureColumns="True" OpenInNewWindow="True"></ExportSettings>
  <ClientSettings>
    <ClientEvents OnCommand="gridCommand" />
  </ClientSettings>
  <MasterTableView DataKeyNames="ID" CommandItemDisplay="Top">
    <CommandItemSettings ShowExportToExcelButton="true" ShowExportToCsvButton="true" ShowExportToPdfButton="true" ShowExportToWordButton="true" />
    <Columns>
      <telerik:GridBoundColumn UniqueName="Id" DataField="ID" HeaderText="ID"></telerik:GridBoundColumn>
      <telerik:GridBoundColumn UniqueName="Name" DataField="Name" HeaderText="Name"></telerik:GridBoundColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>

C#:

 protected void RadGrid1_NeedDataSource(object sender, 
 GridNeedDataSourceEventArgs e)
 {
     DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name");
    for (int i = 1; i <= 5; i++) {
        table.Rows.Add(i, "Name" + i.ToString());
    }

   RadGrid1.DataSource = table;

  }

protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (e.CommandName.StartsWith("Export")) {
        if (!String.IsNullOrEmpty(Request("_downloadToken"))) {
            Response.Cookies.Add(new HttpCookie("_downloadToken", 
            Request("_downloadToken")));         
        }
    }
}