Tuesday, December 28, 2010

SharePoint 2010 - Open a modal dialog from a web part

In SharePoint 2010, the New/Edit/Display form for lists appear as modal dialogs. This uses the Dialog Platform. The modal dialog concept is used when uploading files and also other places in SharePoint 2010.

We can use the same concept if we want to open a modal dialog from a web part. It is pretty simple!

In the web part code, add a prerender event handler:


public MyWebPart()
{
  this.PreRender += new EventHandler(MyWebPart_PreRender);
}


In the prerender handler, register the javascript to open the modal dialog:


private void MyWebPart_PreRender(object sender, System.EventArgs e)
{
  if (!Page.ClientScript.IsClientScriptBlockRegistered(OPEN_DIALOG_SCRIPT))
  {
    string includeScript = @"<script language='javascript'>function OpenDialog(formURL) {var options = SP.UI.$create_DialogOptions(); options.url = formURL; SP.UI.ModalDialog.showModalDialog(options); }</script>";

    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), OPEN_DIALOG_SCRIPT, includeScript);
  }
}


Now, we just need to associate and invoke the javascript OpenDialog function in a hyperlink or a button click. In the below example, I am creating a hyperlink in CreateChildControls method and invoking the function on the hyperlink click:


protected override void CreateChildControls()
{
  HyperLink addListItemLink = new HyperLink();
  addListItemLink.Attributes.Add("align", "left");
  addListItemLink.CssClass = "ms-sitemapdirectional";
  addListItemLink.Text = "Add New Item";
  addListItemLink.NavigateUrl = string.Format(@"javascript:OpenDialog('{0}');", sNavigateUrl);
  this.Controls.Add(addListItemLink);
}


In the above example, the URL in the sNavigateUrl will open in a modal dialog.

No comments: