Monday, October 24, 2011

Passing arguments and handling return value in SP.UI.ModalDialog.showModalDialog

Hi All,

Recently I had a requirement to open a modal window using "SP.UI.ModalDialog.showModalDialog". Also on the modal window we were doing some database operations on the button click and after successful implementation we need to close the modal window and redirect the parent window to the home page of the application.

Also we need to pass some parameters from the parent to the modal window to perform the database operation.

In order to pass value to the modal window, I used the "args" option of the dialog. Also to handle the return value "dialogReturnValueCallback" was implemented. (The list of various options of the dialog can be found here)

Below is the code snippet which I had used to cater my business requirement.

var URLValue ="url of the page which needs to be shown as modal";
//parameters that needs to be passed to the modal window is defined in myArgs
var myArgs = {favoriteName:bookmarkTitle,favoriteURL:bookmarkUrl};
var options = {
url: URLValue,
title: 'Modal Window Test',
allowMaximize: false,
showClose: true,
width:600,
autoSize:true,
args:myArgs,
dialogReturnValueCallback: myDialogCallback
};
var dialogSP = SP.UI.ModalDialog.showModalDialog(options);
});
function myDialogCallback(result,response)
{
if(result ==1)
{
window.location.href = "url of the page where we are redirecting after successful operation";
}
}

The above snippet list down how to open a modal window, passing parameters and defining the return call back. Now we need to make sure that on the button click (submit,OK)on the modal window we pass respective values back to the parent page for further operations.

Below is the code snippet for the same.

function SubmitClicked() {
var results = {
message: "Submmited Successfully",
anothervalue: "Submit"
};
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, results);
}
On the code behind we can register this function like "Button.attributes.add("onclick",SubmitClicked())". This will pass value "1" in the result and we handle the same in the returncallback function "myDialogCallback".

Hope this helps you.. :)

No comments:

Post a Comment