skip to Main Content

I am calling loader on OnClientClick and its loading when the process of downloading in process. But when I try to hide the loader once the process gets completed, it doesn’t works. The loader continously displays and loads.

Here is the code.

function showloadingGif_UPLOAD() {
            document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'inline';
            return true;
        }

        function HideLoader() {
            document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'none';
        }
--loader div

<div id="ContentPlaceHolder1_divShowLoadingGif" class="dvLoader" style="display: none;"> 
                <img id="img2" alt="" src="images/1487.png" />
            </div>


-- button click

<input type="submit" name="ctl00$ContentPlaceHolder1$btnDownloadInfo" value="Report Download" onclick="showloadingGif_UPLOAD();" id="ContentPlaceHolder1_btnDownloadInfo" class="btn btn-primary downnloadReport" />

Also below is the server side code to call the hide function.

protected void btnDownloadInfo_Click(object sender, EventArgs e)
    {
        DataTable dtExcelData = new DataTable();
        try
        {
            CommonUser ObjUser = new CommonUser();
            string strDateFilter = txtDateSelection.Value;
            dtExcelData = ObjUser.GET_EXCEL_REPORT(strDateFilter);


            CommonDB.WriteLog("Dt Count 1 : " + dtExcelData.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());

            if (dtExcelData != null && dtExcelData.Rows.Count > 0)
            {
                CommonDB.WriteLog("Dt Count 2 : " + dtExcelData.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                DownloadReport(dtExcelData);                    
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "<script>HideLoader()</script>", false);
                CommonDB.WriteLog("Dt Count 3 : " + dtExcelData.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('No record found');", true);
            }

        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "<script>HideLoader()</script>", false);
            string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
            CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
        }
    }


public static void DownloadReport(DataTable dtRecord)
    {
        try
        {
           
            string strFilename = string.Empty;
            
            using (XLWorkbook wb = new XLWorkbook())
            {
                CommonDB.WriteLog("Dt Count 3 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                wb.Worksheets.Add(dtRecord, "SheetName");
                strFilename = DateTime.Now.ToString();

                CommonDB.WriteLog("Dt Count 4 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());


                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Charset = "";
                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=JIO_LOS_REPORT_"+ strFilename +".xlsx");
                CommonDB.WriteLog("Dt Count 5 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    CommonDB.WriteLog("Dt Count 6 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                    CommonDB.WriteLog("Dt Count 7 : " + dtRecord.Rows.Count, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());                       
                }
            }
        }
        catch (Exception ex)
        {   
            string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
            CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["AIRFIBER_LOG"].ToString());
        }
    }

2

Answers


  1. The is no a straightforward solution…

    • A regular postback request (a button’s click) – should end with a new entire page render result (+ by a framework called Response.Write + Response.End);

    • A file downloading postback request – should also end with a Response Header = "attachmnent" (+ by a manually called Response.BinaryWrite + Response.End);
      and so on.

    Actually, everything after HttpContext.Current.Response.End(); has no effect for a client / browser. That is why all possible ScriptManager.RegisterStartupScript calls are not part of the response. Therefore, the scheduled JavaScript code is not evaluated / executed. Of course, you can try to omit this call in your code, but it will be necessary to care about possible side effects (to emulate a "native" Response.End).

    Regardless of a way you create an attachment on the server side, it is necessary to download it properly (synchronously).

    The main challenge here is to inform an end-user about (possible) long time (synchronous) operation. You likely saw different kinds of popups or ever newly opened pages with the "… your download will start shortly …" UI on different web services.

    If talking about your code, this solution can implemented smth like this:

    function showloadingGif_UPLOAD() {
      document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'inline';
      setTimeout(function() { HideLoader(); }, DESIRED_MINIMAL_TIMEOUT);
      return true;
    }
    function HideLoader() {
      document.getElementById('ContentPlaceHolder1_divShowLoadingGif').style.display = 'none';
    }
    
    Login or Signup to reply.
  2. i have had something similar before heres my solution:

         <button type="button" runat="server" id="Report_BTN_Report1" class="btn btn-primary" onserverclick="Report_BTN_Report1_OnServerClick" onclick="blockUIForDownload();">
     download
     </button>
    <asp:HiddenField ID="HID_Reports" runat="server" />
    
    <script type="text/javascript">
    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }
    
    var fileDownloadCheckTimer;
    
    function blockUIForDownload() {
        var token = new Date().getTime(); //use the current timestamp as the token value
        $("#HID_Reports").val(token);
        ShowLoadingSplash();
        fileDownloadCheckTimer = window.setInterval(function () {
            var cookieValue = getCookie('fileDownloadToken');
            if (cookieValue == token)
                finishDownload();
        }, 1000);
    }
    
    function finishDownload() {
        window.clearInterval(fileDownloadCheckTimer);
        HideLoadingSplash();
    }
    </script>
    

    and my code behind:

    try{
        var httpResopnse = Response;
    httpResopnse.Clear();
    httpResopnse.Buffer = true;
    httpResopnse.Charset = "";
    
    httpResopnse.ContentType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
    httpResopnse.AppendCookie(new HttpCookie("fileDownloadToken", HID_Reports.Value));
    httpResopnse.AddHeader("content-disposition",
        "attachment;filename=exceldl.xlsx");
    
    using (var myMemoryStream = new MemoryStream()) 
    {
        wb.SaveAs(myMemoryStream);
        myMemoryStream.WriteTo(httpResopnse.OutputStream);
        myMemoryStream.Close();
    }
    
    httpResopnse.Flush();
    httpResopnse.End();
    }
    
    catch (ThreadAbortException)
    {
        // Forced termination. Exit silently.
        // caused by httpResponse.End();
        // .End is needed to complete download properly ?? file is corrupt otherwise
        }
    
    catch (Exception exception)
    {
        Logging.ErrorEntry(exception, "error downloaded");
    }
    
        }
    

    uses a cookie to get weather downloading show/hide splash you replace with what you use to show or hide the loading GIF.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search