How to open popup windows in IE/Firefox and return values using ASP.NET and Javascript

Posted by: Suprotim Agarwal , on 1/25/2008, in Category ASP.NET
Views: 588380
Abstract: With the forums flooded with questions of opening a popup window, passing values to the popup window and then return values back to the parent page using both Internet Explorer and Firefox, I decided to take a plunge into the subject and experiment with an easy implementation. This article explains how to transfer values between the Parent page and a Pop-up window. The code has been tested against IE7 and Firefox.
How to open popup windows in IE/Firefox and return values using ASP.NET and Javascript
 
With the forums flooded with questions of opening a popup window, passing values to the popup window and then return values back to the parent page using both Internet Explorer and Firefox, I decided to take a plunge into the subject and experiment with an easy implementation. This article explains how to transfer values between the Parent page and a Pop-up window. The code has been tested against IE7 and Firefox.
Internet Explorer(IE) contains the showModalDialog() method which proves very effective while creating a modal dialog box and displaying a html document in it. One caveat being, showModalDialog() is not a W3C implementation. So it is not supported in Firefox (as of version 2.0.0.11). Firefox supports the window.open() method. However there is no built in functionality in Firefox that keeps the popup modal. At the most, you can use ‘modal=yes’ to make the popup appear in front. However unlike the showModalDialog() in IE, you cannot restrict the user to access the parent page when the popup is opened in Firefox. In short, it is not truly modal. There are different ways to get around this problem, however in this article, we will only focus on exchanging values between the parent and popup page.
In this article, we will see how to take a simple approach and create a popup window using both IE and Firefox. In the first part, we will pass in the first name from the parent page to the popup window. In the second part, the popup window will reverse the name and return the reversed string to the parent window. All set!! Let us get started.
Part 1 - Passing value to Popup window
Step 1: Open Visual Studio. Create a new website (File > New > Website). Set the location, filename and language of the project.
Step 2: In your Default.aspx, add a label (lblFName), textbox (txtFName) and a button (btnPopup). Set the ‘Text’ property of the label to ‘FirstName’. Similarly set the ‘Text’ property of the button control to ‘Show Popup’.
Step 3: Now add the popup form. Right click your project > Add New Item > Web Form > Rename form as ‘PopupWin.aspx’ and click on Add.
Step 4: In the PopupWin.aspx, add a textbox (txtReverse) and a button (btnReverse).
Well now we have two pages, Default.aspx which is the parent page and PopupWin.aspx which will be the popup page. Let us now pass a value from Default.aspx to the popup window.
Step 5: We will invoke the popup window on the button (btnPopup) click of Default.aspx. To do so, we will use Button.Attribute.Add and call a javascript function that will open the popup window. The javascript function will be contained in a seperate pop.js file which we will create shortly. Add this code in the code behind file of your Default.aspx.
C#
protected void Page_Load(object sender, EventArgs e)
    {
        btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" + txtFName.ClientID + "');");
    } 
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" & txtFName.ClientID & "');")
    End Sub
Over here we are passing the ClientID of the textbox. ClientID is the identifier of the server control, generated by ASP.NET. You must be wondering why I am not passing the value of the textbox directly. Well passing the control has an advantage where there is more than one control that is passed to the popup page. While returning back the values from the popup to the parent page; it helps you to decide and determine which control receives which value. Even though we will be using only one textbox for simplicity, I thought of creating a sample which can be extended later by you to suit your needs. If the use of ClientID is not clear to you, wait till we get to part 2 of this article, and I will again touch upon the subject.
Step 6: Let us now create the javascript functionality which will open the Popup. Right click your project > Add New Item > Jscript file > Rename the file to pop.js. Add the following function to the pop.js file
function InvokePop(fname)
{
        val = document.getElementById(fname).value;
        // to handle in IE 7.0          
        if (window.showModalDialog)
        {      
            retVal = window.showModalDialog("PopupWin.aspx?Control1=" + fname + "&ControlVal=" + val ,'Show Popup Window',"dialogHeight:90px,dialogWidth:250px,resizable:
yes,center:yes,");
            document.getElementById(fname).value = retVal;
        }
        // to handle in Firefox
        else
        {     
            retVal = window.open("PopupWin.aspx?Control1="+fname + "&ControlVal=" + val,'Show Popup Window','height=90,width=250,resizable=yes,modal=yes');
            retVal.focus();           
        }         
}
This function accepts the textbox control, retrieve’s the value of the textbox that needs to be reversed and passes the textbox control and its value to PopupWin.aspx through query string. This is the function which will be called on the btnPopup click.
Step 7: To wire up the .js with your asp.net pages, add a link to the javascript file in both the pages as shown below:
Default.aspx
<head runat="server">
    <title>Parent Page</title>
    <script type="text/javascript" src="pop.js"></script>
</head>
PopupWin.aspx
<head runat="server">
    <title>Popup Page</title>
    <script type="text/javascript" src="pop.js"></script>
</head>
Step 8: In the code behind file of PopupWin.aspx, add the following code at the Page_Load() to retrieve the value from the querystring and display the value in the TextBox ‘txtReverse’, placed in the popup window.
C#
protected void Page_Load(object sender, EventArgs e)
    {
        txtReverse.Text = Request.QueryString["ControlVal"].ToString();
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtReverse.Text = Request.QueryString("ControlVal").ToString()
    End Sub
If you are eager to test the value going from Parent page to the popup window, you can do so now. Make Default.aspx as ‘Set as Start page’ and run the sample. Enter your name in txtFName TextBox and click on Show Popup button. A popup window opens with the value entered in the Parent page.
Part 2 - Passing value from Popup window to the Parent page
In this second part, we will reverse the string and pass the reversed string back to the parent page. To do so, follow these steps:
Step 1: Add additional functions to the pop.js file which will reverse the string and return the string back to the parent page.
// pop.js
function ReverseString()
{
         var originalString = document.getElementById('txtReverse').value;
         var reversedString = Reverse(originalString);
         RetrieveControl();
         // to handle in IE 7.0
         if (window.showModalDialog)
         {             
              window.returnValue = reversedString;
              window.close();
         }
         // to handle in Firefox
         else
         {
              if ((window.opener != null) && (!window.opener.closed))
              {              
                // Access the control.       
                window.opener.document.getElementById(ctr[1]).value = reversedString;
              }
              window.close();
         }
}
 
function Reverse(str)
{
   var revStr = "";
   for (i=str.length - 1 ; i > - 1 ; i--)
   {
      revStr += str.substr(i,1);
   }
   return revStr;
}
 
function RetrieveControl()
{
        //Retrieve the query string
        queryStr = window.location.search.substring(1);
        // Seperate the control and its value
        ctrlArray = queryStr.split("&");
        ctrl1 = ctrlArray[0];
        //Retrieve the control passed via querystring
        ctr = ctrl1.split("=");
}
As you saw in part 1, the value was passed from the parent window to the popup window and was kept in the txtReverse TextBox. The function ReverseString() retrieves the value from this textbox and passes the string to the Reverse() function which reverses the string. The reversed string is then kept in the ‘reversedString’ variable. The ‘RetrieveControl’ splits the query string and identifies the control in the parent page to which the reversed string value is to be sent.
Note: If you observe, in the IE implementation, I am not really making use of the RetrieveControl(), however in Firefox I am. If you remember, in the beginning of part1 , I had mentioned the use of ClientID, using which both controls and their values can be passed to determine which control recieves which value. This is especially needed when there are multiple controls. Well the RetrieveControl seperates the different controls and you can use the variables in this method to return values to the respective contro.l
The value is then returned to the parent window and the popup window is closed.
Step 2: Now in order to use these newly added javacript functions, just call the ReverseString() function on the btnReverse click. To do so, add the onclick attribute to the btnReverse.
<input class="button" type="button" id="btnReverse" value="Reverse value back" onclick="ReverseString();"/>
That’s it. Now test the code. Pass your name from the Parent window to the Popup window and then reverse the string and pass it back to the Parent window.
I would like to mention that there are multiple ways of doing the task demoed in this article. I have seen some cool examples by experts. One of them I would like to mention is that of NC01 where he makes use of properties and ViewState, to pass values to the Popup window. I would encourage you to use this article as a base and try out your own implementations that would work on multiple browsers.
The source code of this article, both in C# and VB.NET, can be downloaded from here. I hope this article was useful and I thank you for viewing it.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Sabena on Monday, March 10, 2008 2:54 PM
Thanks a lot! This really helped.
Comment posted by Vivek on Thursday, March 20, 2008 10:03 AM
Excellent M8..One of the best stuff i read recently. Keep it up..The Interview question section is also very useful :)
Comment posted by nasir on Friday, March 21, 2008 5:14 AM
great article.... i tested it just fine....
Comment posted by manoj on Friday, March 21, 2008 2:36 PM
great work....really simple yet powerfull method..
Comment posted by Piyush Varma on Friday, March 21, 2008 3:05 PM
Very informative with step-by-step instructions. It will be useful in my forthcoming project. Thanks much!
Comment posted by Rakesh Bridgraj on Friday, March 21, 2008 9:16 PM
Great article it will be very useful in my next project. It is so simple and yet so powerful great job keep it up
Comment posted by Tom Dewey on Sunday, March 23, 2008 1:26 AM
Thanks I was struggling with passing back a value.

In the popup window when the button is clicked, the popup window disappears, but a new IE window is created with the popup contents.  Exiting the parent does not exit this new pop-up.

I thought it might be something VS 2008, so I defined an application as Web3a under IIS and tried to invoke the application through //localhost/Web3a/default.aspx.  At this point I received the following error --
Compiler Error Message: CS0016: Could not write to output file 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\web3a\09c6d743\61b4afb9\App_Web_default.aspx.cdcab7d2.
khu6vp20.dll' -- 'Access is denied. '

Any suggestions?
Thanks
tom
Comment posted by Suprotim Agarwal on Sunday, March 23, 2008 11:02 AM
Hi Tom,
Couple of things that you could try for that error:
Go to the Temporary folder > Right click > Sharing and Security > Security tab > Add 'Network Service' and give it Full Control'
If that does not solve the issue, check this link:
http://blogs.msdn.com/viag/archive/2007/02/09/
compiler-error-message-cs0016-could-not-write-to-
output-file-c-windows-microsoft-net-framework-v1-1-4322-
temporary-asp-net-files-myapp-fadda49e-bbdb0b87-eqdatzch-
dll-access-is-denied.aspx
Comment posted by Tom on Tuesday, March 25, 2008 12:26 AM
Suprotim,
Thanks. Changed Windows/Temp as you suggested and compile error goes away.  Found similar info under Microsoft help and support.

Comment posted by GH on Wednesday, March 26, 2008 7:05 AM
This is a very out of date way of getting values from a user.
A modal is virtually impossible in Firefox as you have to constantly force a focus on the window in question - not a good thing to do.
It's much cleaner impersonating a modal by using an iframe and an absolutely positioned DIV over the top of your content to achieve the same look - if done properly you then don't require maintenance of two separate code bases for different browsers.

In addition, the way you're rendering this form potentially opens it to script injection attack from a hacker as you're not escaping values between the page load and the render which is a security risk.

Finally - onclick attributes use javascript in 99% of modern browsers by default and do not require the javascript: prefix.
Comment posted by Aric Smith on Wednesday, March 26, 2008 10:49 AM
Very nice and detailed article.

However looking at current security issues, like XSS, CSRF, injections this implementation makes web site highly vulnerable.

So exposing data/control names of the form openly is risking the web site.

Think about XSS, CSRF, javascript injections.
Comment posted by Suprotim Agarwal on Thursday, March 27, 2008 10:18 AM
Hi,
Thanks for the comments GH and Aric.
Aric: That's a good point you made. I would like to point the users towards this article which contains some great points how to protect a site from Injection attacks. Read more at:
http://msdn2.microsoft.com/en-us/library/bb355989.aspx
Thanks.
Comment posted by GH on Monday, March 31, 2008 12:12 PM
A couple more here....
http://msdn2.microsoft.com/en-us/library/ms998274.aspx

http://support.microsoft.com/kb/252985
Comment posted by TinaKhattar on Wednesday, April 2, 2008 12:01 AM
I faced this strange issue today.... i had a asp link button on my aspx page, i added a attribute for its onclick in the code behind to call a javascript function .That javascript function opens another aspx page in a new browser
issue:- this works second time and not first time.
And when i use Page.RegisterStartupScript, this is the issue:-
Back button issue
Reply to all
Forward
Reply by chat
Filter messages like this
Print
Add to Contacts list
Delete this message
Report phishing
Report not phishing
Show original
Show in fixed width font
Show in variable width font
Message text garbled?
Why is this spam/nonspam?
javs sawhney to memberservices
   
show details 6:28 PM (4 hours ago)
   
   
Reply
   
   
Hi,

when you add javascript code to your page using Page.RegisterStartupScript and you redirect to some other page and now if you use browser's back button and come to the original page the script add get's executed automatically.
If i am showing a confirm and clicking "yes" button i redirect user to some other page through javascript's window.location.href='ABC.aspx'
and if i press browser's back button on ABC.aspx page i see the confirmation box on the previous page.

So is there any way that i can avoid this.

thnx..
Kindly suggest something
Comment posted by Hoanvu Tran on Thursday, April 17, 2008 1:38 AM
Thanks for sharing yours knowledge
Comment posted by Priya on Sunday, April 27, 2008 10:46 PM
How to pass value from one apge to another page????

I mean how to pass Gridview value from one page to another???????????
Comment posted by Sumathi on Sunday, April 27, 2008 10:49 PM
I want to know how to pass a gridvalue from one page to another gridview in another page using the select in the gridview?

I also want to know how to save checkbox data into the database???


Is this feasile???
Pls help....
Very Urgent....
Pls help me....PLS...
Thanks Alot....
E-mail me...Thanks...For ur valuable time
Comment posted by Suprotim Agarwal on Monday, April 28, 2008 11:21 AM
Sumathi, Priya: Check this article over here to pass values from GridView to another page

http://www.dotnetcurry.com/ShowArticle.aspx?ID=147
Comment posted by NoSpam on Monday, April 28, 2008 12:46 PM
Clicking the ShowPopup button does not open up the new browser window, the only thing that I have done different is that I included the pop.js javascript in the actual .aspx page. Please help
Comment posted by Mistere on Friday, May 2, 2008 1:13 PM
  Hi, So a note that wasn't highlighted in the article. the button on the popup page must be an input button, and not an asp .Net button? When i try this code with the .Net button, it does not close the popup window, but re-sizes it larger, and pushes it to the back.
Comment posted by Suprotim Agarwal on Saturday, May 3, 2008 6:53 AM
NoSpam: That's because the default.aspx will not be able to access the js kept on PopWin.aspx. It's best to keep it as a seperate file.
Mistere: Thanks for your comment. In Part 2: Step 2, it is mentioned that the tag looks similar to the following:
<input class="button" type="button" id="btnReverse" value="Reverse value back" onclick="ReverseString();"/>
The ReverseString() calls window.close();

Anyways thanks for pointing that out explicitly for future users.
Comment posted by gaurav on Wednesday, May 28, 2008 8:02 AM
i want to know how to display an error message dialogue box when a particular website is opened and also the website must get closed and only the error message must remain on the desktop.

if u have the answer pls mail it to me
Comment posted by Jb on Wednesday, May 28, 2008 2:48 PM
When I'm back in the code behind of the parent after the postback, where is the value returned in the javascript function ReverseString() (window.returnValue) located? In other words how do I get at the returned value using C#? If I'm in the btnReverse event, what variable holds the returned value? Thanks for your help.
Comment posted by Jb on Wednesday, May 28, 2008 3:02 PM
When I'm back in the code behind of the parent after the postback, where is the value returned in the javascript function ReverseString() (window.returnValue) located? In other words how do I get at the returned value using C#? If I'm in the btnReverse event, what variable holds the returned value? Thanks for your help.
Comment posted by sezer on Tuesday, June 24, 2008 9:22 AM
About Redirect to other web address // html code --

http://html-lesson.blogspot.com/2008/06/redirect-to-web-addres.html
Comment posted by HATE POPUPS on Tuesday, August 19, 2008 12:41 PM
NOOOOOOOOOOOOOOOOO!!!

Please, do not perpetuate the evil that is popup windows!

If you have to do dialog of some sort, do it on the same page with an absolutely positioned div.
Comment posted by Malay Thakershi on Wednesday, August 20, 2008 12:12 PM
I debugged your code in IE7 and FF. Worked very well. In IE7 though it was setting the textbox to 'undefined' when I close the popup using 'X'. So I added that condition. Second thing, I added UpdatePanels so that the page doesn't get fully refreshed. It worked for me. I don't understand why the last comment by 'Hate Popups' is so against popup windows. If I have a business application, search and use type of functionality can be implemented using this. I also hate advertisement popups. Thank you.
Comment posted by santosh kumar on Thursday, August 21, 2008 3:14 AM
thanks,
great work done, I use this code , it will be work error free.

santosh kumar
http://www.operativesystems.com
Comment posted by Suprotim Agarwal on Thursday, August 21, 2008 9:20 PM
Jb: The reversed string is contained in the text box
window.opener.document.getElementById(ctr[1]).value = reversedString;

Santosh, Malay: Thanks for the comments and the tips.

Comment posted by SURFThru.com on Thursday, August 28, 2008 11:09 AM
I wrote one of these a few years ago and was looking for any other thoughts on doing this work.

This is a great example and one you can actually download, run, and test in seconds.

Great work!

www.SURFThru.com
Comment posted by sergiotarrillo on Tuesday, December 16, 2008 4:32 PM
It is a copy?: http://www.c-sharpcorner.com/UploadFile/strongmind/aspnet07202008041948AM/aspnet.aspx.

What is the original?

Saludos,
Comment posted by Suprotim Agarwal on Thursday, December 18, 2008 9:58 AM
Thanks for informing. The publishing date should answer that question. It is shameful that authors tend to adopt plagiarism. Anyways, I have informed c-sharpcorner.com about the same. Hopefully, they will remove the article from their site.
Comment posted by dot developer on Saturday, January 24, 2009 2:11 AM
Thankyou
Comment posted by Sangam Uprety on Wednesday, February 18, 2009 6:18 AM
Thanks for the tips. Here goes how to open new windows in asp.net web page using javascript. http://dotnetspidor.blogspot.com/2009/01/open-new-window-in-aspnet-web-page_28.html
Thanks.
Comment posted by shishir on Thursday, February 26, 2009 2:37 AM
i want to divide my grid column in two sub part.
can it possible.
Comment posted by Suprotim Agarwal on Thursday, February 26, 2009 6:38 AM
Shishir: Two Sub parts as in like shown over here?
http://forums.asp.net/t/1368658.aspx
Comment posted by asdasd on Friday, May 15, 2009 7:32 AM
eewrw
Comment posted by kumar on Tuesday, June 2, 2009 11:05 AM
thanks http://www.planetsourcecode.in
Comment posted by Deepali Kamatkar on Wednesday, August 19, 2009 5:55 AM
sahii..
Comment posted by Phil Thorn on Thursday, September 3, 2009 5:35 AM
The AJAX Control Toolkit has a ModalPopup control. I've used that in the past to great  success, and found it much simpler than this approach. May have also worked in FireFox but was a while ago- worth an effort if your website has AJAX already.
Comment posted by adrian samler on Thursday, September 30, 2010 6:01 AM
This doesn't work for me (I copied code AND tried downloading it). I get an error on clicking the "Rerverse back" button.
"Object Expected" (Line 21, char 1)
Comment posted by lk lk,m nm on Wednesday, April 20, 2011 4:20 PM
thanks
Comment posted by kiran on Tuesday, October 11, 2011 6:32 AM
thanks. its working fine.
Comment posted by sarawut on Sunday, March 25, 2012 10:00 PM
thanks. its working fine.
How return multi values ?

help me
Comment posted by Danny on Wednesday, April 4, 2012 9:27 AM
Works fine for single-line textbox.  But for multiline textbox, it converts all text to single-line style, even in the popup textbox (even if the popup textbox is also multiline).  In other words, you lose all newlines.  Any easy fix?
Comment posted by Inayat on Wednesday, December 19, 2012 4:30 AM
Nice article save my day.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel