Recently as I was creating a SharePoint web part for a DMC client I ran across a problem which really stumped me. At first, I thought what I had was an easy problem to solve: how does one open a popup window from C# in a web part? I did a lot of research regarding the popup window problem and I discovered that the problem was not addressed in the manner which I needed literally anywhere on the Internet. So after a lot of time spent, energy wasted, and coffee drank I finally was able to engineer a solution, and it is a little trickier than expected. 

Now I know what you’re thinking “That’s easy, I have been doing that in HTML since 1999.” Well, that’s what I thought too, but it was not quite that easy and requires a little bit of work. Just to review, it is easy to add a hyperlink in HTML which launches in a popup window:

<a href = “http://servername.com” target = “_blank”>Link to text</a>

Now that’s about as simple as it gets in computers, but what about doing the same thing via JavaScript? Well, that is also pretty straightforward:

<script language = “javascript” type = “text/javascript”>

window.open(‘http://servername.com’, ‘windowname’, ‘width=XXX, height=YYY’);

</script>

Once again, not too bad right? So if we have a click event procedure in a C# code behind file such as: 

///<summary>
/// btn click handler
///</summary>
///<param name="sender">Sender</param>
///<param name="e">Event Args</param>
protected void _btn_Click(object sender, EventArgs e)
{
	//some code executes here

	//launch popup window, BUT HOW?
}

How do we launch a popup window when the web part’s HTML is loaded? I tried several ideas such as rendering the JavaScript code above into the web part’s HTML. However, the JavaScript was rendered well above the HTML for the surrounding SharePoint web page, which caused it to fail. So, obviously, this wouldn’t work, so how exactly does one get this to work?

The answer actually is a combination of C# code and JavaScript. What we need to do is pass the web address in the query string to the page via a Response.Redirect statement, then parse the query string in JavaScript code, and launch a popup window. To do this we must first insert the following code in to our ASCX file for the web part: 

<script language = "javascript" type = "text/javascript">
    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        var ret = "";
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                ret = pair[1];
                break;
            }
        }
        return ret;
    }

    var popupurl = getQueryVariable("popupurl");
    if (popupurl != "") {
        window.open(popupurl, "mypopup_window", "width=500, height=500");

        //cleanses querystring
        if (window.location.href.indexOf("popupurl") >= 0) {
            var posqs = window.location.href.indexOf("?");
            if (posqs >= 0) {
                var refreshurl = window.location.href.substring(0, posqs);
                window.location.href = refreshurl;
            }
        }
    }
</script>

Then we need to do a redirect in the C# file this way: 

///<summary>
/// btn click handler
///</summary>
///<param name="sender">Sender</param>
///<param name="e">Event Args</param>
protected void _btn_Click(object sender, EventArgs e)
{
	//some code executes here

	//launch popup window
	string URL_TO_POPUP = "http://servername.com";
        string szQSParameter = "popupurl=" + URL_TO_POPUP;
	string szRedirect = Request.Url.Scheme + "://" +
                            Request.Url.Host + ":" + 
			    Request.Url.Port.ToString() +
                            Request.Url.AbsolutePath;
	if (szRedirect.Contains('?') == true)
	{
		szRedirect += "&" + szQSParameter;
	}
	else
	{
		szRedirect += "?" + szQSParameter;
	}
	Response.Redirect(szRedirect);
}

Doing this makes it easy for our web part to pop up windows from the C# code behind file when needed.

I hope this helps you on your way to developing compelling web parts for SharePoint 2010. We here at DMC are experts with SharePoint and Microsoft technologies, and would love to help you implement whatever solution your business needs.

Don't hesitate to contact DMC if you need some help on a SharePoint project (we are especially good at helping our cllients integrate data from other systems into SharePoint dashboards).

Share this page:

Comments

-->
# Anonymous User
Monday, December 27, 2010 10:49 PM
http://fast-loans-blog.info/archives/2082
-->
# Nick
Monday, January 10, 2011 8:49 AM
this is easier:

StringBuilder sbPopup = new StringBuilder("\n ");

this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Popmywindow", sbPopup.ToString());

Works fine.
-->
# Nick
Monday, January 10, 2011 8:53 AM
It does allow me to paste my code, but it's the typical script tag with your open window statement.
-->
# Janhavi
Thursday, March 03, 2011 7:04 AM
Hello William Sir,
I am currently working on the same problem that you have explained above "Open a pop up window from SharePoint web part". Though I have read the entire solution, I am not able to implement it properly. Will you please elaborate on it? It will be great if you tell me all the intermediate steps between creating a web part and adding a pop up window in it.
Thanking you in anticipation.
-->
# Igor M.
Friday, December 02, 2011 8:18 AM
why don't you want to use SP 2010 Jscript API function SP.UI.ModalDialog.showModalDialog ?
-->
# suresh.p
Wednesday, February 08, 2012 5:05 AM
Hi ,how to display sharepoint pop window from link button please tel me

Post Comment

Name (required)

Email (required)

Website

Enter the code shown above in the box below