Execute javascript code at the end of the event handler

I am building an ASP.NET web application with C #. When I click the button, I show the boot image while the database query is running. Then I dynamically create the Excel file and send it to the client as follows:

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xlsx");
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(p.GetAsByteArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End(); 

I get a dialog box and the boot image remains there.

I tried to place a javascript function call (using ClientScript.RegisterStartupScript function) before the code above, this did not work. As far as I understand, all javascript codes are run after all the code is executed, but in this case it does not execute at all as soon as the file is sent to the client.

I also tried to create a separate thread and delete the uploaded image. I set a breakpoint to track it, the code in the stream executes, but the image still remains there.

Does anyone have an idea how this can be handled? Thank!

+3
source share
3 answers

You can send or send only 1 mime type in one request / response cycle. (My knowledge in this area is controversial).

However, you can develop a hack for this. Use an iframe on the client to "download the file." You can specify it srcin an ashx file that does the same.

You need to hook up the onload iframe event so that your web page somehow knows that the download is complete; this is where you can execute your logic.

Solution update:

, , I, , !

, iframe onload- , - . onload iff , url, src, . , . , !

, ?!

, cookie . - cookie. , - cookie, , . :

http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx

, ( ) ( iframe, ). :

WebForm1.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.FileDownload.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>iFrame Download</title>
    <script type="text/javascript" src="Scripts/jquery-2.1.0.min.js"></script>
    <script type="text/javascript" src="Scripts/jquery.cookie.js"></script>
    <script type="text/javascript">
        function foo() {
            console.log('foo');
            //execute post-download logic here
        }
        $(function () {            
            $('input').click(function () {
                //make sure we get rid of the 
                //cookie before download
                $.removeCookie('downloaded');

                var intrvl = setTimeout(function () { //this function polls for the cookie through which we track that the file has indeed been downloaded
                    console.log('timer');
                    var value = $.cookie('downloaded');
                    if (value == 'true') {
                        clearTimeout(intrvl);
                        foo();
                    }
                }, 1000);

                //this initiates the download
                $('iframe').attr({
                    'src': 'download.ashx?id=' + $('#tbxRandomNumber').val()
                });

            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="tbxRandomNumber" runat="server"></asp:TextBox>
        <input type="button" value="Download" />
        <iframe src="about:blank" style="display:none"></iframe>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Next Random Number" />
    </div>
    </form>
</body>
</html>

jquery cookie, cookie.

download.ashx:

using System;
using System.Web;

namespace WebApp.FileDownload
{
    /// <summary>
    /// Summary description for download
    /// </summary>
    public class download : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {            
            context.Response.ContentType = "text/plain";
            context.Response.SetCookie(new HttpCookie("downloaded","true")); //setting cookie in the response
            string id = context.Request.QueryString["id"] == null ? "NULL" : context.Request.QueryString["id"];
            string str = string.Format("Content with id {0} was generated at {1}", id, DateTime.Now.ToLongTimeString());

            context.Response.AddHeader("Content-Disposition", "attachment; filename=test.txt");
            context.Response.AddHeader("Content-Length", str.Length.ToString());
            context.Response.Write(str);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
+3

, . . - , , .

Excel, :

HttpContext.Current.Response.Clear();

, JavaScript. .

( ), , - onclick. , .

, . Excel <iframe> onload, .

Excel, OnClick. , , , onload <iframe> IE.

+1

javascript , . , yo :

txtHidden.Text = "Hola Mundo"

You should check the value on the page load:

<script type="text/javascript">
$(document).ready(function(){
  if($("#txtHidden").length > 0 && $("#txtHidden").val() != '')
  {
    alert($("#txtHidden").val());
  }
});
</script>

You can put this in a web user control. Another solution:

<div class='button' id='btnGenerateDownload' onClick='GenerateDownload(this)'>
 Click here <div id='loadingImage' class='loadingImage'></div>
</div>

JQuery

function GenerateDownload(caller)
{
   //add loading gif:
   var $loagingGIF = $(caller).children('#loadingImage').eq(0);
   $loagingGIF.addClass('loadingImage');
   var fileGeneratorUrl = 'ghFileGenerator.ashx';
   var downloadHandlerUrl = 'ghDownloadHandler.ashx';
   $.post({data: "File1"}, function(response){
     //remove gif
     $loagingGIF.removeClass('loadingImage');
     if(response != '') //file key
     {
       downloadHandlerUrl += '?key=' + response;
       var $link = $("<a />").attr('href', downloadHandlerUrl).html('download');
       $link.appendTo($(caller));
     }
   });
}

CSS

.loadingImage{background: transparent url(images/loading.gif);}

.ashx:

 string filekey = context.Current.Request.Form("key");
0
source

All Articles