Display real-time export status improvement

Utilizing the Java Script below to display a loader once the Export To Excel button is clicked.

<script type="text/javascript">
    function showProgress() {
        var updateProgress = $get("<%= UpdateProgress1.ClientID %>");
        updateProgress.style.display = "block";
    }
</script>


<asp:Button ID="btntoExcel" runat="server" Text="Export to Excel"  onclick="btntoExcel_Click" OnClientClick="showProgress()" Width="115px" 
                CssClass="styleShowData" Font-Size="Smaller" />

Currently, everything is functioning correctly, but the loader continues to load after saving the file in the system as well.

I am unsure of how to halt the loading process since the JavaScript specifies it as:

updateProgress.style.display = "block"

Any advice on resolving this issue would be greatly appreciated.

Thank you in advance.

Full Code Below:

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="ViewReport.aspx.vb" Inherits="ViewReport" %>

Status Report

    <script type="text/javascript">
        function showProgress() {
            var updateProgress = $get("<%= UpdateProgress1.ClientID %>");
            updateProgress.style.display = "block";
        }

        function hideProgress() {
            var updateProgress = $get("<%= UpdateProgress1.ClientID %>");
            updateProgress.style.display = "none";
        }   
    </script> 

<div runat="server" id="divPopupWindow" align="Left" style="position: relative; top: -11px; left: 0px; background-color: #C8B49B;">
    <marquee behavior="alternate"><asp:Label ID="mqHeader1" runat="server" Text="Scrolling Employee Info"></asp:Label></marquee>

    <br />
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
    <br /><br />

    <asp:UpdatePanel runat="server" ID="UpdatePanel_1">
        <ContentTemplate>

        <div runat="server" id="divMyPageWidth_2" align="Left" style="position: relative; height: 10%; left: 0px; background-color: #C8B49B;">

        <asp:Button ID="btntoExcel" runat="server" Text="Export to Excel"  onclick="btntoExcel_Click" OnClientClick="showProgress()" Width="115px" 
            CssClass="styleShowData" Font-Size="Smaller" />

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:Button ID="btnGotoMainPage" runat="server" Text="Goto Main Page"  
        Width="118px" CssClass="stGotoMainPage" 
        Font-Size="Smaller" />

                <br />
                <table>
                    <tr>
                        <td class="style2">
                            <asp:DropDownList ID="ddlStatusSelection" runat="server">
                                <asp:ListItem Selected="True">Approved</asp:ListItem>
                                <asp:ListItem>Pending</asp:ListItem>
                                <asp:ListItem>Rejected</asp:ListItem>
                            </asp:DropDownList>
                        </td>

                        <td class="style3">
                            <asp:DropDownList ID="ddlShowRecordsCount" runat="server">
                                <asp:ListItem Selected="True">25</asp:ListItem>
                                <asp:ListItem>50</asp:ListItem>
                                <asp:ListItem>100</asp:ListItem>
                                <asp:ListItem>200</asp:ListItem>
                                <asp:ListItem>300</asp:ListItem>
                                <asp:ListItem>400</asp:ListItem>
                                <asp:ListItem>500</asp:ListItem>
                                <asp:ListItem>All</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                        <td>
                            <asp:Button ID="Button1" runat="server" Text="Show Data"  
                            CssClass="styleShowData" />
                        </td>
                    </tr>
            </table>

        <div runat="server" id="divMyPageWidth" align="Left" style="position: relative; background-color: #C8B49B; overflow: scroll">
                <asp:GridView ID="gvScreenToExcel" runat="server" AutoGenerateColumns="false" HeaderStyle-Wrap="True" Height="190px" Width="380px" 
                    BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
                    RowStyle-Wrap="false"  Font-Size="Small" >
                    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                    <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                    <SortedAscendingCellStyle BackColor="#FFF1D4" />
                    <SortedAscendingHeaderStyle BackColor="#B95C30" />
                    <SortedDescendingCellStyle BackColor="#F1E5CE" />
                    <SortedDescendingHeaderStyle BackColor="#93451F" />
                    <AlternatingRowStyle BackColor="#FFE7CE" />
                    <Columns>
                        <asp:BoundField DataField="Rec_Num" HeaderText="Record #" />
                        <asp:BoundField DataField="Remarks" HeaderText="Remarks" />
                    </Columns>
                </asp:GridView>
            </div>

        </div>
        </ContentTemplate>

        <Triggers>
            <asp:PostBackTrigger ControlID = "btntoExcel" />
        </Triggers>

    </asp:UpdatePanel>

    <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel_1">
    <ProgressTemplate>
        <div class="modal">
            <div class="center">
                <img alt="" src="Loader.gif" />
            </div>
            </div>
        </ProgressTemplate>
    </asp:UpdateProgress>
  </div>
</form>

Answer №1

Provided here are some key details about the situation and information given before presenting a solution:

  • A crucial point to note is that the actual download process needs to take place during a standard postback, not an asynchronous one. Therefore, correctly registering the "asp:PostBackTrigger" is essential in most cases. Otherwise, you might encounter the dreaded Sys.WebForms.PageRequestManagerParserErrorException.

  • It is important to understand that there is no straightforward method to receive notifications in client-side code or execute any startup scripts (such as RegisterStartupScript) from the code-behind when the HttpResponse.End method is used, typically during export operations.

In instances where it is necessary to display a custom progress indicator instead of relying on the browser's default indicator during the download process, consider implementing the following approach:

  • Subscribe to the client-side events of the UpdatePanel through Sys.WebForms.PageRequestManager,
  • Initiate an asynchronous request to show the progress indicator. For example, designate the "btntoExcel" button as an asp:AsyncPostBackTrigger. This will trigger the progress indicator to appear,
  • Click the "btntoExcel" button to kick off a sequence. Handle the button's server-side Click event, and save the generated EXCEL file either in memory or within a server directory,
  • Handle the "endRequest" event in the client-side UpdatePanel. By this point, the progress indicator should be hidden. Trigger an authentic postback to the server (e.g., by incorporating a hidden "asp:PostBackTrigger" button or utilizing a raw "__doPostBack" function),
  • Handle the Click event of this button on the server side to execute the actual download (using the previously created file).

The complete functional code below has been tested with the supplied markup:

<script type="text/javascript">
    function showProgress() {
        //var updateProgress = $get("<%= UpdateProgress1.ClientID %>");
        //updateProgress.style.display = "block";
    }
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_initializeRequest(prm_InitializeRequest);
    prm.add_endRequest(prm_EndRequest);
    function prm_InitializeRequest(sender, args) {
        alert("Starting Update Panel Async Request... Saving File... Displaying Progress Indicator...");
    }
    function prm_EndRequest(sender, args) {
        alert("Update Panel Async Request Finished. File Saved, But Not Yet Downloaded. Progress Indicator Should Be Already Hidden. Starting Real Download...");
        var btnDoRealDownloadClientObject = $get("<%= btnDoRealDownload.ClientID %>");
        btnDoRealDownloadClientObject.click();
    }
</script>

<asp:UpdatePanel runat="server" ID="UpdatePanel_1">
    <ContentTemplate>
        ...
       <asp:Button ID="btntoExcel" runat="server" Text="Export to Excel" OnClick="btntoExcel_Click" OnClientClick="showProgress()" ... />
        <asp:Button ID="btnDoRealDownload" runat="server" OnClick="btnDoRealDownload_Click" style="display: none" ... />
        ...
    </ContentTemplate>

    <Triggers>
        <%--<asp:PostBackTrigger ControlID="btntoExcel" />--%>
        <asp:AsyncPostBackTrigger ControlID="btntoExcel" />
        <asp:PostBackTrigger ControlID="btnDoRealDownload" />
    </Triggers>

</asp:UpdatePanel>

<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel_1">
    ...
</asp:UpdateProgress>

//C#
protected void btntoExcel_Click(object sender, EventArgs e) {
    Session["SavedFile"] = SAVE_FILE_AS_MEMORY_STREAM;
    ...
}

protected void btnDoRealDownload_Click(object sender, EventArgs e) {
    MemoryStream stream = Session["SavedFile"] as MemoryStream;
    ...
    Page.Response.BinaryWrite(stream.ToArray());
    Page.Response.End();
}


'VB
Protected Sub btntoExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
    Session("SavedFile") = SAVE_FILE_AS_MEMORY_STREAM
    ...
End Sub

Protected Sub btnDoRealDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim stream As MemoryStream = CType(Session("SavedFile"), MemoryStream)
    ...
    Page.Response.BinaryWrite(stream.ToArray)
    Page.Response.End
End Sub

Answer №2

After completing the export logic in your code behind's btntoExcel_Click event, make sure to include the following line of code.

Utilize ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "hideProgress();", True) for hiding the progress bar.

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

Click on the link to open in a new tab and redirect the current window to a different website

Currently, my form action is set to "_blank" in order for the pdf document I am generating to open in a new tab/window. While this works correctly, I am looking to also have the original page redirect to a different URL simultaneously. Are there any ways ...

Why is it that Backbone.js occasionally becomes "disconnected" from the server?

Whenever I click rapidly on certain elements, Backbone.js seems to malfunction. The AJAX functionality stops working entirely. Switching routes and trying to load new content results in nothing appearing due to issues with the AJAX requests. To resolve th ...

What causes the variance in AJAX errors between IE and Chrome browsers?

Consider the code example provided below: <script> function xyz() { $.ajax({ type: "GET", url: "https://zx/xyz/uvw", timeout: 6000, dataType: "jsonp", ...

The state is not being configured accurately

In my ReactJs project, I have a model Component with a picture that is displayed. I want to pass the data of the clicked picture, which can be neither raw data nor a URL. I have implemented a handler that can delete the picture (if pressed with the Ctrl k ...

Refresh the store value in React Flux when the route is changed

I have a straightforward setup using React and Flux. I am creating new posts with actions and stores, but the issue is that when the user navigates to another route and then returns, the this.postAdded value remains the same. The store: class NewPostsSto ...

Update the table seamlessly to display fresh new data without the need to reload the entire page

I'm looking for a way to display recently added data on a listing page without having to reload the entire page. Currently, I have to refresh the page each time I add new data to my database in order to see the updates. Is there a way to view the new ...

Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array. Below is the service where I am retrieving data from Firebase: File name: subcategory.service.ts export class SubcategoryService { subcategoryRef: Angula ...

What could be causing the service method in the controller not to be called by Node JS?

In my current Node JS project, the folder structure of my app is as follows: src │ index.js # Main entry point for application └───config # Contains application environment variables and secrets └───controllers # Hou ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

Is it possible to extract data from a table by adjusting Javascript in the inspector tool? The page is only showing today's data, but I'm interested in retrieving historical data by going back

My Desired Action: I am interested in extracting data from the 2nd and 3rd tables on this page. However, the data displayed is specific to the current 'day'. I wish to access readings from September 1st and import them into a Google Sheet. Speci ...

What methods can I use to ensure that images remain at the forefront without relying on Z-Index?

My website design includes a feature where an image pops up next to an underlined word when hovered over. The issue is that the images are supposed to always be on top, but the underlined words are appearing over them. I suspect there is a conflict in the ...

Make sure that a div and a label are perfectly aligned in a horizontal

I am trying to align a label next to a div horizontally in my asp.net form, but I am having trouble accomplishing this. Below is the code snippet that I have been working with. Can someone please help me? Code Snippet: <div class="modal" id="passwo ...

Execute JavaScript code prior to sending a Rails form

Before submitting the form, I would like to trigger the html5 geolocation javascript code. Here's how I envision the process: upon form submission, the user is prompted with a geolocation popup. After allowing access, the form data should be processed ...

What could be causing the error when trying to use a PUT request with fetch in Vue?

Whenever I attempt to send a PUT request, an error pops up on the console. export function putUserData() { fetch(`${url}/user/${getCookie("ID")}`, { method: "PUT", headers: { "Authorization": `B ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

React blogging site's administrative dashboard

https://i.sstatic.net/M6fUJ.png I am currently in the process of developing a blogging platform using MERN technology. Specifically, I am focused on creating a restful API with Node.js, Express, and MongoDB. The frontend, built with React, consists of thr ...

Using jQuery to Save Data Locally in a JSON File

Just a heads up; all of my work is kept local. I've been on the hunt for ways to write to a JSON file from a JS script using jQuery. Many methods involve PHP, but I don't have much experience with that language and would prefer to avoid it for no ...

Ensure that all input fields on the webpage are validated when clicked using jquery

Having just embarked on my journey with jquery, I am giving it my all. Within my asp.net mvc project, there is a page filled with x-editable inputs. I decided to create a simple button: <input type="button" class="btn btn-info" id=& ...

Transferring a File from FileUpload Control to FTP Server in C#

I am currently facing an issue with uploading a file from a FileUpload control to a newly created folder on FTP. The folder creation is successful, however, I am encountering difficulties in uploading the file. It appears that my filepath to the source fi ...

Utilize a Random Color Generator to Match Background Color with Border Color in Full Calendar

I'm currently developing a full calendar to showcase a clear and aesthetically pleasing schedule for my client. I am attempting to assign a unique color to each event by generating random colors on every page load using codes. However, I have encounte ...