Blokjes

Blokjes

Tuesday, December 8, 2009

Howto: Disable SharePoint's double postback block

I was working on a SharePoint web part today when I came across a very annoying issue.

The idea of my web part was quite simple:

- Display a form with various fields and a "Generate Report" button
- When a user clicks the "Generate Report" button, a Word-file is dynamically created and made available for download.

The button is a common asp:Button control:
<asp:Button runat="server" id="CreateReport" Onclick="CreateReport_Click" text="Create Report">

The event handler is also quite simple:
protected void CreateRapport_Click(object sender, EventArgs e)
{
  PersistFieldValues();
  Response.Redirect("/_layouts/MyProject/GenerateWordReport.ashx");
}

The PersistFieldValues() method stores all form field values in a Session variable. These values are then used by the GenerateWordReport web handler to generate a Word file.
 
The user is redirected to the web handler which generates a Word file dynamically and uses the following header information to make sure the user gets the proper "Open/Save As/Cancel" dialog for the document:
response.AddHeader("Content-Disposition", "attachment; filename=Report.doc");
response.ContentType = "application/ms-word";

The user can now open the document, but in the back the original web form is still being presented in the browser, without having been refreshed. This is caused by the fact that a redirect has been done to the HttpHandler which sent binary content to the browser. 
 
Unfortunately, the form is no longer responsive, it's dead. You can no longer press buttons or any other links that cause a postback. This behavior is caused by the fact that as soon as you do a postback to the server, SharePoint makes sure in Javascript that you can't submit the same form twice.
 
At first I thought this was an asp.net issue, but after spending an awful lot of time on Google I finally found out asp.net wasn't the source of my problem, SharePoint was. The following discussion provided me with a good solution for my problem: http://www.telerik.com/community/forums/aspnet-ajax/grid/export-to-excel-in-sharepoint-application-page.aspx
 
The solution I implemented
In the webpart, I rendered a small piece of Javascript that avoids SharePoint from blocking multiple postbacks:

if (!Page.ClientScript.IsStartupScriptRegistered("SUPPRESSSUBMITWRAPPER"))
{
  Page.ClientScript.RegisterStartupScript(this.GetType(),
  "SUPPRESSSUBMITWRAPPER",
  @"
_spBodyOnLoadFunctionNames.push(""SuppressSubmitWrapper"");
function SuppressSubmitWrapper()
{
  _spSuppressFormOnSubmitWrapper = true;
}
",
true);
} 

No comments:

Post a Comment