SharePoint 2010 PopUp Dialogs

Introduction:

In this article I will describe that how to create popup screen or model popup or dialog box in sharepoint 2010 which will look same as how sharepoint OOB popup screen appears on view/edit of list item.
Also I will explain that how to trigger C# code from popup on ok or cancel or on popup load. As well as; I will also explain that how to refresh main screen from popup on ok or cancel.

This article will have these below things:-
1. Custom framework to get popup screen (It use SharePoint 2010 dialog framework).
2. Dot Net user control with respect to each popup. Means; if you need 2 popup then create 2 user controls.
3. Sample user control which use this custom framework.
4. Download link to get all custom framework source code and sample user control source code.

Note: In end of article i will provide a link to download my custom framework classes which are explained in this article.

Approaches:

Approach 1. You can create each aspx page with respect to each popup.
Approach 2. You can create each user control with respect to each popup.

Approach 1
This approach I don’t like because of below 2 reasons:-
a) this page can be used only in popup. If I want to use on main page then I cant or its harder.
b) With this approach if you try to do operation in popup screen on DB (insert/delete etc) then it throws access denied error for read access users for some reason.

Approach 2
I like this approach since I can use User Control in popup screen as well as on main screen. User controls are reusable. Also it does not throw error for read access user.
In this article I will explain about 2nd approach.

Detail of 2nd Approach:

Step 1: we will create framework by which we can create n number of popups.
Step 2: we will create popup screen (user control) which will use step 1 framework.

1
2
3
4
5
6
7
Note: 
For this 2nd approach, Using your WSP package, 
User control should be placed here:-
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\SPDialogFramework
AND
JS should be placed here:-
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\scripts\SPDialogFramework

SharePoint master page or pagelayout should have below JS references:-

1
2
3
4
<script type="text/javascript" src="/_layouts/scripts/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/_layouts/scripts/jquery-latest.js"></script>
<script type="text/javascript" 
 src="/_layouts/scripts/SPDialog Framework/SPDailogRelatedJS.js"></script>

See below image which shows where file goes after deployment:-

14_hive_filePath

Step 1 (Custom framework):

Here we will create custom framework by which we can get popup like how sharepoint 2010 list get on view/edit of item. For this we will create below things:-

- DotNet ASPX page named as “SPDialogPage.aspx”
- DotNet c# class named as “SPDialogBoxLayoutPageBase.cs”
- DotNet c# class named as “SPDialogEventHandler.cs”
- DotNet c# interface named as “IDialogBox.cs”
- JavaScript file named as “SPDailogRelatedJS.js”

1. “SPDialogPage.aspx”

This is main page which load into popup screen. Here i receive user control name as parameter.
Load this user control into my page and place into placeholder.
That means you pass any user control to this page; it will load and place into placeholder.
Here is few line of code:-

1
2
3
4
5
6
7
string userControlName = Request.QueryString["UserControlFileName"].ToString();
string completePathName = "~/_controltemplates/SPDialogFramework/" + userControlName;
UserControl uc = (UserControl)LoadControl(completePathName);
ContentPlaceHolder cpHolder = (ContentPlaceHolder)this.Master.FindControl("PlaceHolderMain");
PlaceHolder ucHolder = (PlaceHolder)cpHolder.FindControl("UserControlPlaceHolder");
ucHolder.Controls.Clear();
ucHolder.Controls.Add(uc);

2. “SPDialogBoxLayoutPageBase.cs”

This would be the base class for popup page. where i end the operation on close/cancel of popup.

1
2
3
4
5
6
7
8
protected void EndOperation(int result, string returnValue)
        {
            string closeModal = String.Format(CultureInfo.InvariantCulture,
            "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose
            ({0}, '{1}');</script>", new object[] { result, returnValue });
            this.Page.ClientScript.RegisterStartupScript(base.GetType(),
            "CreatePopup", closeModal, false);
        }

3. “SPDialogEventHandler.cs”

This class called by a delegate in popup screen to find that what action triggered like close or cancel.

1
2
3
4
5
6
public delegate void AddEventHandlerToSPDialogEvent(object sender, SPDialogEventHandler e);
        public SPDialogEventHandler(int result, string list)
        {
            ReturnValues = list;
            dialogResult = result;
        }

4. “IDialogBox.cs”

The popup user control should inherit this interface which make sure that you implement an event.

1
2
3
4
    interface IDialogBox
    {
        event AddEventHandlerToSPDialogEvent ResultOk;
    }

5. “SPDailogRelatedJS.js”

Java script will be called 2 times. 1st; when you call popup from main page. and 2nd; when you close popup page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var calledUsercontrolName;
 
//================================================================
//--SP Dialog Pop-up Common JS to all user control
//================================================================
 
function OpenSPDialogBox(calledUCName, passParamValue, modaltitle, modalwidth,
                         modalheight, CallBackFunctionName) {
    ExecuteOrDelayUntilScriptLoaded(function () {
 
        var options = {
            title: modaltitle,
            url: SP.Utilities.Utility.getLayoutsPageUrl(
            "/SPDialogFramework/SPDialogPage.aspx?UserControlFileName=" 
            + calledUCName + passParamValue),
            width: modalwidth,
            height: modalheight,
            showClose: true,
            dialogReturnValueCallback: window[CallBackFunctionName]
        };
 
        calledUserControlName = calledUCName;
 
        SP.UI.ModalDialog.showModalDialog(options);
        return false;
    }, "sp.js");
}
 
//================================================================
//--JS specific to "MainScreenSample.ascx" control
//================================================================
// result would be 0 or 1
// return value would be any string. Here i use for succes/error message.
function MainScreenSample_CallBack(result, returnValue) {
    var msg = returnValue;
 
    if (result == 1) {
        $('input[id$=btnTrggerMainPagebyPopupScreen]').trigger('click');
    }
    else {
        if (!returnValue)
            msg = "No data was updated."
    }
    SP.UI.Notify.addNotification(msg);
}

Step 2 (Sample user control):

Here we will create user control “PopupSample.ascx” for popup screen and “MainScreenSample.ascx” for main page (it can be a web part also, if you require). This main page will call “DialogFrameWork.aspx” which will load “PopupSample.ascx” user control in popup page.

Note:
1. Refer my article which explain that how to load user control in web part :
http://sharepoint.infoyen.com/2012/04/11/create-and-deploy-user-control-in-sharepoint-using-feature/
2. Refer my article which explain how to pass parameter from webpart to user control:-
http://sharepoint.infoyen.com/2012/06/03/pass-web-part-property-value-to-user-control/

MainScreenSample.ascx user control

Here the main important part is how to call popup screen and how to listen popup close action. see below code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        protected void Page_Load(object sender, EventArgs e)
        {
            this.txtFirstName.Text = "Avinash";
            this.txtLastName.Text = "Dad";
            string firstName = this.txtFirstName.Text;
            string lastName = this.txtLastName.Text;
 
            // Below code is done to call the popup screen
            string passParamValue = "&FirstName=" + firstName + "&LastName=" + lastName;
            string callModal = "javascript:OpenSPDialogBox(" + "'" + "PopupSample.ascx" + "','" 
            + passParamValue + "','Popup Sample'," + "'420'," + "'420" + "',
            'MainScreenSample_CallBack');return false;";
            this.CallPopup.Attributes.Add("OnClick", callModal);
        }
 
        protected void btnTrggerMainPagebyPopupScreen_Click(object sender, EventArgs e)
        {
            // In popup screen you update name into sharepoint list or sql database.
            // Then here you again query to sharepoint list or sql database to get the update data.
            //right now i will assign hard code value.
            this.lblName.Text = "Avinash Kumar Dad, work as SharePoint Project lead.";
            asyncMainPanel.Update();
        }

PopupSample.ascx user control

Here you receive parameter from main page. Do operation as you required. In last you trigger an event using “AddEventHandlerToSPDialogEvent” to send message to main screen. See below code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public event AddEventHandlerToSPDialogEvent ResultOk;
protected void Page_Load(object sender, EventArgs e)
        {
            firstName = this.Page.Request.QueryString["FirstName"];
            lastName = this.Page.Request.QueryString["LastName"];
        }
        private void InsertIntoCustomSqlDB(int dialogResult)
        {
            //here you can perform custom logic
            //You can insert these data into sharepoint list or custom database like MS SQL
 
            bool isInsertSuccess = false;
            //isInsertSuccess = custmDBGateway.InsertEmpDetails(lastName,firstName); //
 
            if (this.ResultOk != null)
            {   // Here dialogResult is 1. that means we have clicked on ok button
                // Here dialogResult is 0. that means we have clicked on cancel button
                if (isInsertSuccess)
                    ResultOk(this, new SPDialogEventHandler(dialogResult, "Data updated successfully"));
                else
                    ResultOk(this, new SPDialogEventHandler(dialogResult, "Data could not update."));
            }
        }
        protected void OKBtn_Click(object sender, EventArgs e)
        {
            try
            {// Here dialogResult is 1. that means we have clicked on ok button
                int dialogResult = 1;
                InsertIntoCustomSqlDB(dialogResult);
            }
            catch (Exception ex){            }
        }        
        protected void CancelBtn_Click(object sender, EventArgs e)
        {
            try
            {
                int dialogResult = 0;
                if (this.ResultOk != null)
                {// Here dialogResult is 0. that means we have clicked on cancel button
                    ResultOk(this, new SPDialogEventHandler(dialogResult,"Action Cancelled"));
                }
            }
            catch (Exception ex) { }
        }

See below image which shows sample popup display in sharepoint:-

spdialog_samplepage

Below are link to download the source code:-

Download SharePoint DialogFramework
Download Sample UserControls which use this framework

Thanks!

calendarOctober 24, 2012 · cardInfoyen · comments7 Comments
tagTags: ,  · Posted in: SharePoint, SharePoint 2010

7 Responses

  1. Arujn - February 6, 2013

    Hi,

    I am creating a page for Frequently Asked Questions (FAQ). There are couple of questions. I do not want users need to scroll down for reading each and everything. I want to provide hyperlinks to the text. If the person clicks on a question one popup window needs to appear with text. Is it possible for me to do it in sharepoint 2010. if it is possible pl guide me.

    Thanx
    Arjun

  2. Anand - February 19, 2013

    Hi,

    I am working on a similar project, where I have created a menulist in left webpart.

    On click of each link, I would like to load a popup called as Non Disclosure Agreement.
    It should load for each link just once per session and then it should not popup again until you log backin.

    On clicking on “accept” the next page should load on the same page itself. No new window.

  3. Taher - February 21, 2013

    Thank you a lot..very interesting wolrk..Can you please upload the whole visual studio solution pour us..beginners in sharePoint world.

  4. Infoyen - April 3, 2013

    you need to design the solution. in my view it can be:-
    1. question and answer stored in sharepoint list
    2. question and answer stored in sql database.

    In both case you can create 1 custom web part and 1 user control :-
    1. 1st webpart to display all question on main page.
    2. 2nd should be user control which display answer based on question.

    This user control you load using my popup framework. So user control (which have answer) automatically will appear in popup.

    Thanks!
    Avinash

  5. Infoyen - June 9, 2013

    My solution should work. You need to include your session logic as per your requirement.

  6. shruti - August 27, 2013

    Hi,
    I need to open open an application page in popup window. I tried with your solution but not able to open. Can you guide please? Which namespaces are required for using SP.UI.Modaldialog function?

  7. Infoyen - August 29, 2013

    I have given link to download sourcecode in bottom of my article.
    This will help you to understand to code.

Leave a Reply

Spam Protection: , required

myworldmaps infoyen