I am exporting a gridview to excel, using .Net 4.0 in a web application, on page load and need for the file to be generated and then the page to be redirected to the calling
In JavaScript:
function refresh() { document.location.reload(true); }
button:
<td valign="top" style=" width:100px ">
<asp:Button runat="server" ID="btnX" Text="X" CssClass="ui-button ui-widget ui-state-default ui-corner-all ui-button-text ui-state-hover" OnClientClick="refresh();" Width="180px" />
</td>
The problem is Response.End() send the last bits of the page to the client in order to complete the request. In your case, the request contains the file.
One possible solution is be to open a new page for the download and keep the redirect in the current page.
You can't do both open so you might want to try setting the link to the generated xls file in a new window or as source to a iframe
I tried opening a separate page through ScriptManager that will download my file while doing the redirect in my original page.
So I added below code in my main page:
string strScript = "<script language='javascript'> window.open('CommonDownload.aspx','Report');</script>";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "clientScript", strScript, false);
Response.Redirect("Page.aspx");
And then added the download code in the Page_Load method of my CommonDownload page. I passed some of the info I needed in the CommonDownload page through through the session.
I suggest to add a redirect header. Something like this:
Response.AddHeader("Refresh", "3; url=index.html");
Where 3 is time of the delay and index.html is url you need to redirect to
I added the target="_blank"
to the link that takes me to the page. So when it opens in a new window, it send the excel sheet ot the browser, and closes the page as it has nothing else to do after the Response.End();
Hope this helps. Worked for me.