ASP.NET No Postback After File Download in SharePoint

We have an ASP Button control in SharePoint that allows the user to download a file. When the button is clicked, the file is written to the page’s response and gets handled by the browser like any other file download.

[csharp light=”true”]
Response.AddHeader(“content-disposition”, “attachment; filename= ” + Uri.EscapeDataString(file.Name));
Response.AddHeader(“Content-Length”, file.Length.ToString());
Response.ContentType = GetMimeType(file.Name);
Response.WriteFile(Server.MapPath(“~/” + file.Name));
[/csharp]

The problem was that the form would become completely unresponsive after this button was clicked.

Reason:

SharePoint has a JavaScript variable called _spFormOnSubmitCalled that gets set to true to prevent any further submits. Since our download button does not refresh the page, this variable remains true and thus, causes all other buttons to stop working.

Workaround:

We set this variable back to false in the button’s client click handler:

[html light=”true” wraplines=”true”]
<asp:Button
ID=”btnDownload”
runat=”server”
text=”Download”
OnClientClick=”setFormSubmitFalse()” />
[/html]

[javascript light=”true”]
function setFormSubmitFalse() {
setTimeout(function () {
_spFormOnSubmitCalled = false;
}, 100);
}
[/javascript]

The timeout is needed to ensure that SharePoint first sets _spFormOnSubmitCalled to true, before we set it back to false again.