SharePoint 2010 - Closing A Modal Dialog Within An UpdatePanel Programmatically

9 August 2012

SharePoint 2010 provides lots of nice of JavaScript helpers and methods, one category of which involves Modal Dialogs (eg the default behaviour when you view / edit a list item in a list). We can pretty easily create a modal dialog with a call to SP.UI.ModalDialog.showModalDialog(options) (and you can take a look at this blog post for a little more detail).

So, let's imagine we open a dialog box to an Application Page, and we want a few custom buttons which do different things on the server, and then close the dialog. Is it possible to close the JavaScript modal dialog from the C# backend? Sure is! You basically just need to write out the following Javascript onto the page, like so:

context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
context.Response.Flush();
context.Response.End();

However (and this is the part that caught me out), the above won't work if you're using an UpdatePanel in your Application Page, for a number of different reasons. So if you've got a modal dialog opening an application page in SP2010 which uses an UpdatePanel and you'd like to close it from codebehind, you can't use the Response object - instead, you'll have to use the ScriptManager and the RegisterClientScriptBlock method.

ScriptManager.RegisterClientScriptBlock(
    theButton, // control or UpdatePanel that will be rendered
    typeof(YourPage), "UniqueKey", // makes your script uniquely identifiable
    "window.frameElement.commitPopup();", true);

The JavaScript registered above will only run when the specified control (in this case, the control with ID 'theButton') is updated or modified - in my case, I just had a asp:Panel which I changed from hidden to visible, but there's plenty of other ways you can decide to organize when the JavaScript will be called.

Not too hard, right? But man did I spend way too long on this... Thanks to Ruben who provided the answer on StackOverflow. Happy coding everyone!

Tags: Javascript, modal dialog, ScriptManager, UpdatePanel, SharePoint 2010

Add a Comment

No Comments