Sunday, May 24, 2015

Open Modal dialog in SharePoint

You can use a JavaScript function for this purpose.

1) When you don't require a return from the Modal dialog.

    function openModalWindow(strPageURL) {
        var options = {
            url: strPageURL,
            title: "Title goes here",
            showClose: true,
            width: 600,
            height: 400,
            allowMaximize: false
        };

        SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
    }

2) When a return value is required to be captured by the Parent page

Include a callback parameter in the options specified

Option 1: Include in the options parameter collection

function openModalWindow(strPageURL) {
        var options = {
            url: strPageURL,
            title: "Title goes here",
            showClose: true,
            width: 600,
            height: 400,
            allowMaximize: false
            dialogReturnValueCallback: CloseDialogCallback
        };

        SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
    }

Option 2: Place the code after other option parameters are defined

var options = {
                url: strPageURL,
                allowMaximize: false
                showClose: true
            };
            options.dialogReturnValueCallback = Function.createDelegate(null, CloseDialogCallback);

            SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);


In the invoked function, you could specify the actions to do once the Modal Dialog closes, such as refreshing the parent page

function CloseDialogCallback(dialogResult, returnValue) {
            if (returnValue.d) {
               /*Do something */
            }
            if (dialogResult == SP.UI.DialogResult.OK) {
                SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.RefreshPage', SP.UI.DialogResult.OK);
            }
        }

3) Closing the Modal Dialog (Add script to the page in the Modal Dialog)

This can be done in two ways

  • Without referencing the SP.UI.Dialog.js
function closeOnCancel() {
            window.frameElement.commonModalDialogClose(0 /* 0 for cancel */, 'Cancelled');
        }

function closeOnOk() {
            window.frameElement.commonModalDialogClose(1 /* 1 for ok */, 'OK result');
        }

- OR - 

  • using the SP.UI.Dialog.js

Reference the JavaScript on your page.
<script src="/_layouts/15/SP.UI.Dialog.js" type="text/javascript"></script>

function closeOnCancel() {
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel, 'Cancelled');
        }
function closeOnOk() {
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'OK result');
        }

To call these JavaScript functions from server side code use ScriptManager:

ScriptManager.RegisterStartupScript(this, this.GetType(), "closeScript", "closeOnOk();", true);

However, the final JavaScript function might give out a JavaScript error in some Internet Explorer versions.



Saturday, May 23, 2015

JavaScript Takeaways for .Net Developers

1) Capture server controls where ClientIDMode is not set to Static

document.getElementById("<%= txtRule.ClientID %>").value

2) Storing Session value in JavaScript variable

var userAttempts = '<%= Session["userAttemptSession"] %>';


3) Manipulating Hidden field values

/*Get value*/
var hitCountContainer = document.getElementById("hdnMyCount")
var hitCount = parseInt(hitCountContainer.value);
hitCount = hitCount + 1;

/*Set Value*/
hitCountContainer.value = hitCount.toString()

4) Invoking a post-back (without any parameteres)

__doPostBack('', '');

5) Invoking post-back (including parameter passing)

__doPostBack('hdnMyCount', hitCount.toString());

Accessing the post-back parameters in Page_Init

string controlName = Request.Params["__EVENTTARGET"];
string controlValue = Request.Params["__EVENTARGUMENT"];

This example may be useful in a scenario where you need the client-side updated values during the Page_Init. Reason is that the values are not accessible at this point of the ASP.Net Page Life Cycle. If you need to access hidden fields during Page_Load this is not necessary as the values are already accessible by that time (of the ASP.Net Page Life Cycle). Dynamically generating Controls in an application page on user request (eg: add new row having ASP.Net controls) would be an ideal scenario.

FYI:
There is a nice little image of the ASP.Net Page Life Cycle in this MSDN Blog. Adorable isn't it ?   ;) The very essence of ASP.Net forms programming !!
         
6) Sending multiple parameters in JavaScript postback

Here I send two JavaScript variables count & type.

__doPostBack('addNew', JSON.stringify({ count: count.toString(), type: selectedText}));

In the server side capture using the following

/*Using directive*/
using System.Web.Script.Serialization
...
...
/*Code logic*/
string receivedArgs = Request.Params["__EVENTARGUMENT"];
var arguments = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(receivedArgs);
var countValue = arguments["count"];
var typeValue = arguments["type"];