Thursday, May 30, 2013

Sharepoint pop up window from code behind in visual webparts

You can use the below piece of code to open a sharepoint pop up window from code behind .This is done by calling a jaavascript function on button click from the code behind

In the ascx page use the below code
<script type="text/javascript">
function OpenDialog(strPageURL, width, height, title, args) {
ExecuteOrDelayUntilScriptLoaded(test, "sp.js")
function test() {
var dialogOptions = SP.UI.$create_DialogOptions();
dialogOptions.url = strPageURL; // URL of the Page
dialogOptions.width = width; // Width of the Dialog
dialogOptions.height = height; // Height of the Dialog
dialogOptions.title = title;
dialogOptions.args = args;
dialogOptions.allowMaximize =
false;
dialogOptions.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
// Function to capture dialog closed event
SP.UI.ModalDialog.showModalDialog(dialogOptions); // Open the Dialog
return false;}
}


// Dialog close event capture function
function CloseCallback(strReturnValue, target) {

if (strReturnValue === SP.UI.DialogResult.OK) // Perform action on Ok.
{//alert("User clicked Ok!");
}if (strReturnValue === SP.UI.DialogResult.cancel) // Perform action on Cancel.
{//alert("User clicked Cancel!");}
}
 
</script>

In the button click event call the below code  

var url = "http;//www.google.com";

ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "CustomScript", "OpenDialog('" + url + "', 994, 1000, 'Title', null);", true); 


We are using the code
ExecuteOrDelayUntilScriptLoaded(test, "sp.js")

because the sharepoint API for sharepooint modal pop up dialog window is present in  sp.js sometime this is loaded after the javscript function is called which will result in error.Hence inorder to get over it we force the loading of sp.js before the function is executed ...


Also add below links in page

<SharePoint:ScriptLink ID="ScriptLink1" Name="sp.ui.dialog.js" LoadAfterUI="true" Localizable="false" runat="server"></SharePoint:ScriptLink>
<%--<Sharepoint:ScriptLink ID="ScriptLink2" Name="SP.UI.Dialog.debug.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>--%>
<SharePoint:ScriptLink ID="ScriptLink3" Name="sp.js" LoadAfterUI="true" Localizable="false" runat="server"></SharePoint:ScriptLink>




To redirect to page or close popup on button click see the link Close popup

2 comments:

  1. Ur post is very helpfull thanks

    ReplyDelete
  2. Does it work on PreSave action? I tried but it's not giving expected results. On newform.aspx page when I click Save(Submit) button I want to open pop up with some questionnaire and Ok and cancel buttons. If I click Ok then newform.aspx page should save the values to list. If I click Cancel then system should not save values to list and popup box should be closed and I should be redirected to newform.aspx page.

    ReplyDelete