Loyalar
Loyalar

Reputation: 2163

Execute Javascript after postback with cleared response in C#

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).

Upvotes: 0

Views: 1934

Answers (1)

Turay Melo
Turay Melo

Reputation: 114

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.

Upvotes: 1

Related Questions