ASP.NET No Postback After File Download in SharePoint

May 15, 2014

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.

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

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:

<asp:Button 
    ID="btnDownload" 
    runat="server" 
    text="Download" 
    OnClientClick="setFormSubmitFalse()" />
function setFormSubmitFalse() {
    setTimeout(function () {
        _spFormOnSubmitCalled = false;
    }, 100);
}

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