Using SP.UI.Dialog and SP.UI.Notify from code behind

SharePoint 2010 comes with the SP.UI framework. This is a JavaScript library which you can use to interact with the SharePoint UI. I wanted to use the SP.UI framework to display a dialog which is only shown when condition are met in code behind.

ValidationDialogWebPart

When I placed the JavaScript in the web part I got a null reference error. The problem originated from the SP.UI object model not being loaded. Especially because it did work when I executed the script on the OnClick event of a button.

The solution is provided by the SP.SOD.executeOrDelayUntilScriptLoaded method. It will wait to execute the function you provide until the script you refer is completely loaded.

ExecuteOrDelayUntilScriptLoaded(ShowDialog, "sp.js");

Within my project I added a JavaScript file containing my method “ShowDialog()” to show the dialog. Within my web part I perform the validation and call the CreateDialog() method.

/// <summary> /// Registers the javascript supporting showing dialog. /// </summary> /// <remarks> /// When calling this method, the dialog is shown /// to the user and blocks the page below. /// </remarks> private void CreateDialog() { // Define the name and type of the client scripts on the page. string csname = "ShowDialogScript"; Type cstype = this.GetType(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the startup script is already registered. if (!cs.IsStartupScriptRegistered(cstype, csname)) { StringBuilder js = new StringBuilder(); js.Append("<script type='text/javascript'>"); js.Append("ExecuteOrDelayUntilScriptLoaded(ShowDialog, 'sp.js');"); js.Append("</script>"); cs.RegisterStartupScript(cstype, csname, js.ToString()); } }