0

When a user clicks a button on my website I make an excel file on server-side and write it in the response.

HttpResponse httpResponse = Page.Response;
httpResponse.ClearHeaders();
httpResponse.ClearContent();
httpResponse.Clear();
httpResponse.Buffer = true;
httpResponse.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"" + fileName + "\";");
httpResponse.ContentType = "application/vnd.xlsx";
httpResponse.Charset = "";

using (MemoryStream memoryStream = new MemoryStream())
{
    workbook.SaveAs(memoryStream);
    memoryStream.WriteTo(httpResponse.OutputStream);
    memoryStream.Close();
}

httpResponse.Flush();
httpResponse.End();

When I'm done writing this file, I would like a JavaScript script block to run, but I can't seem to make this work. I have heard that when I clear the response, I can't write a script block with the Page.ClientScript.RegisterStartupScript (deprecated?), since the user doesn't get the same page as the response, but I am hoping there's a workaround.

The button that makes the postback and fetches the file is not in an UpdatePanel, so I am unable to use the PageRequestManager.add_endRequest function that is implemented there. And I can't put the control into an UpdatePanel, since it won't allow me to write a file in an async postback.

Is there any other way to trigger a javascript function at the end of a postback? A JavaScript interval function that checks if a postback is in progress (or finished) is also an acceptable solution as well (but as far as I know, there is no way for JavaScript to "check" if a synchronous postback is in progress).

Community
  • 1
  • 1
Loyalar
  • 2,131
  • 4
  • 24
  • 44
  • 1
    Look at [this](http://stackoverflow.com/a/4168965/4052433) and [this](http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/) for some workarounds for this issue (issue: no browser event for file download) – pln Oct 17 '14 at 07:02
  • Holy crap, that is genius. It works. Thanks! You can submit it as an answer and I'll accept it when I can, if you want. – Loyalar Oct 17 '14 at 07:36

1 Answers1

1

The Response.End() aborts the thread and sends the execution to Application_EndRequest. Nothing can be done after that. You can either download the file or execute the javascript. But there is this solution using iframes.

Community
  • 1
  • 1
Turay Melo
  • 114
  • 5