Display an alert using JavaScript once the RadGrid Telerik web component has finished exporting data

I'm currently utilizing a Telerik web component called RadGrid that is connected to an Asp.Net ObjectDataSource. This component allows the data it is linked to be exported into Excel, PDF, or Word formats. However, I am facing an issue where I am unable to trigger a JavaScript alert once the file download is complete. I have attempted using the OnResponseEnd method in JavaScript, but it has not yielded the desired result.

Any recommendations or suggestions?

Here is the codebehind code that I have implemented 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 here is a shortened 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"
                    AllowFilteringByColumn="True"
                    AllowPaging="True"
                    AllowSorting="True"
                    OnItemCreated="RadGrid1_ItemCreated"
                    PageSize="4"
                    OnGridExporting="RadGrid1_GridExporting"
                    OnPdfExporting="RadGrid1_PdfExporting"> 
</telerik:RadGrid>

Answer №1

When performing an export that requires a full postback, ajax is not feasible as it limits the returned data from the post. This can make handling the complete event challenging. One workaround is to use a cookie that will be returned after the full postback of the export process. The method outlined in the following tutorial demonstrates using this approach to address a similar issue related to displaying an AjaxLoadingPanel during export.

The solution involves adding a cookie to the form on the server side once the export is completed. Simultaneously, the client continuously checks for this cookie's presence. When the client detects the cookie, it signifies that the export has finished.

Show loading panel when exporting RadGrid

Below is a functional sample code tailored to your specific 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS complications with data flow

I am facing an issue in my code where I have a function nested inside a directive that fetches query results successfully. However, I am struggling to store these results in a factory and then pass them to a controller. Below is the code snippet of the di ...

JQuery is capable of hiding a div using the .hide() method but is unable to reveal it using the

I am currently working on a basic webpage that includes a question and a set of radio buttons. Depending on the option selected by the user, the question will be hidden and either a correct or incorrect message will be displayed, both of which are initiall ...

Utilizing Vue.js: Disabling button on image carousel when there is no "next" photo accessible

This is my initial experience with Vue. I am attempting to assemble a slideshow using an array of images. I have successfully managed to disable the "previous" button when the user reaches the beginning of the slideshow, but I am encountering difficulties ...

Building a multi-page application with ExtJs MVC

I'm new to MVC, especially when it comes to extJs. I want to implement the MVC approach in my project. I came across a tutorial at , which provided an example with only one page. In this example, they used app.js to load extjs views. My question is, w ...

What is the standard text displayed in a textarea using jQuery by default

My goal is to display default text in a textarea upon page load. When the user clicks on the textarea, I want the default text to disappear. If the user clicks into the textarea without typing anything and then clicks out of it, I'd like the default t ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Restricting JQuery pop-up to be shown only once

I'm looking for a solution to have a pop-up appear only once when the mouse leaves the screen. I'm not very experienced with coding, so I'm struggling to figure out how to achieve this. // Implementing Exit Intent function addEvent(obj, ev ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Compile LESS scripts in Visual Studio Team Services as part of the build process

Currently, I am in the process of deploying an ASP.NET Web Application to an Azure Website using VSTS's Continuous Integration. Everything is running smoothly, except for the compilation of LESS files. Upon reviewing the build steps, I did not come a ...

Exploring the depths of Nesting in Next.js Links

After trying to nest the Badge inside the Link element and wrapping it in an <a> tag, I managed to resolve some errors but one persists: https://i.sstatic.net/o1WfA.png import { useState } from 'react'; import Link from 'next/link&apo ...

Integrating MVC capabilities into a WebForms website project

Our website is primarily built using webforms (not a web app with a .csproj file). While we do not plan on fully migrating to MVC, we have identified certain requirements where MVC would be a more suitable solution. After researching the topic, it seems th ...

Passing a jQuery dialog variable for use in a php function using ajax

I am struggling to successfully pass variables from jQuery to a PHP function using AJAX. I have included the necessary HTML and script, but I'm confused as to whether the PHP file specified in the "url:" parameter should be external or can it be follo ...

Limit the focus to the dialog box using JavaScript

Is there a way to limit the tab and shift-tab key focus to only cycle through input elements within a specific popup dialog in HTML? I have a div with a high z-index that contains these input elements, and I want to restrict the keyboard navigation to st ...

Using VueJS: accessing this.$store within component data property

I am interested in utilizing the data from my Vuex store in both my app and template. My Vuex store: var Vue = require('vue'); var Vuex = require('vuex'); Vue.use(Vuex) let store = new Vuex.Store({ state: { user: ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...

Three.js - Intense shadow cast on mesh's facial features

I have designed a chest model using blender, hand-painted a texture for it, and placed it in an environment rendered with Three.js. However, I am facing an issue with an unusually extreme shadow on the front face of the chest: Here is my setup for the Ren ...

React components do not re-render when the context value changes

The issue with React not re-rendering when the context value changes persists I am using tailwindcss, React(v18.2.0), and vite(3.2.4). I have already attempted i want that clicking on TodoItem should change the completed value in the todo using React con ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

Utilizing data attributes to configure jQuery plugin settings

Having trouble assigning options to an array value in a jQuery plugin using data attributes. When referencing the data attribute with a class selector: $('.tm-input').tagsManager( { prefilled: $('.tm-input').data('loa ...

Enhancing response accuracy with Prisma queries in Nest Js

Server-Side Logic: const studentAssignments = await this.prisma.classesToStudents.findMany({ where: { studentId: +studentId, classStatus: 'completed', }, select: { classes: { select: { projects: { ...