Close SharePoint Modal Dialog from within Silverlight

This took me a fair bit of searching to figure out, and there’s probably a number of better (or at least different) ways of doing this, but this seems to work for me, it’s just a few lines of code, it’s non-invasive, and you don’t have to tweak the page hosting your Silverlight object. 

So… imagine you’ve got a Silverlight application running inside of a SharePoint modal dialog.  You want to allow the user to click a button in Silverlight (say, a “Save” button after saving some data to some web service using WCF), to dismiss the modal dialog.

This is simply a combination of two techniques, shown here and here.  You’d put this code in the code-behind of your user control, e.g. MainPage.xaml.cs.  Using MVVM you could bind an ICommand to your button, or if you’re not using MVVM, you could just put this in the Click event of a button in the code behind.

 public void CloseWindow()
 {
     var Script = HtmlPage.Document.CreateElement("script" );
     Script.SetAttribute("type", "text/javascript" );
     Script.SetProperty("text", "function CloseDialog() { window.frameElement.commitPopup(); }" );
     HtmlPage.Document.DocumentElement.AppendChild(Script);
     HtmlPage.Window.Invoke("CloseDialog" );
 }
 

Comments

  1. Thanks for posting this. I used your code and added a URL parameter to the commitPopup function so now the modal dialog closes and my form gets redirected.

    StringBuilder js = new StringBuilder();
    js.Append("function CloseDialog() {");
    js.Append(string.Format(" window.frameElement.commitPopup('{0}');", this.RedirectUrl));
    js.Append("}");

    ReplyDelete
  2. You're welcome, and, nice addition! Thanks!

    ReplyDelete

Post a Comment

Popular posts from this blog

Parsing MSTEST results (.trx files) programmatically (in C#)

The description for Event ID ( 3 ) in Source ( TFSShellExt ) cannot be found.

Request.Browser.IsMobileDevice