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


Recently, a friend of mine asked about how to open popup (modal) windows in IE/Firefox and return the values back to the main page. although there are tons of question/answers about this subject in ASP.NET forums, nearly none of them was comprehensive enough. For this reason and to answer my friend’s question I am going to explain how to open a dialog box, how to pass initial values to this dialog box, how to get the values back and so on.

Internet Explorer(IE) contains the showModalDialog() method which proves very effective while creating a modal dialog box and displaying a html document in it. Dishearteningly, showModalDialog() is not a W3C implementation. So it is not supported in Firefox. 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.

I have written a small but exhaustive sample web site whose link is shown at the end of the article.

As it was mentioned earlier, to open a dialog we can use showModalDialog (for IE) or window.open (for FireFox) JavaScript functions to open a dialog. Both functions take 3 arguments:

  1. The URL of the page to show.
  2. Caption of the dialog window.
  3. Settings of the dialog window.

The most used setting items are as follows:

  • center: yes/no (indicates weather the dialog must be screen centered)
  • resizable: yes/no (indicates weather the dialog window is resizeable)
  • status: yes.no (indicates weather a Status Bar is added to the dialog window)
  • dialogWidth: n (the width of the pop up window. like : 300px)
  • dialogHight: n (the hight of the pop up window. like : 200px)

Both window.Open and window.showModalDialog functions return a value . This value is set within the called page (dialog page) by assigning the result value to window.returnValue. However, since we are ASP.NET developers, we are most likely to use the result in Server-Side code so I do not feel like very much to get the result value with JavaScript code.

By the way, write a JavaScript function and call it whatever you wish, like OpenDialog(), and put it in <head>…</head> section of your caller (main) page:

function OpenDialog()
{
window.showModalDialog(‘Child.aspx’,”,’center:yes;resizable:yes;

status:no;dialogWidth:3030px;dialogHight:200px’);
}

the above example indicates that OpenDialog function will open Child.aspx in a modal window whose width is 300px .

Now at your caller page, put a Button and name it btnOpenDialog. Afterwards go to properties window and put the following line next to OnClientCliek property:

javascript:OpenDialog();

To create the pop-up window we must create a page named Child.aspx. In my demo code, I have put a CheckListBox there with 3 items (Apple, Orange and Banana) in it. We also need two buttons named btnOK and btnCancel.

We do not need to write anything on code behind for btnCancel. All we have to do is to write the following code snippet into btnCancel.OnClientScript property:

javascript:window.close();

In order to return a value, we can assign it to window.returnValue property but I really don’t feel like to do it because in most cases we obtain this value from some server-side code (we are ASP.NET developers!) and if we insist on using window.returnValue , we will have to mixup some server-side and client-side code together which makes our code unclear.Moreover, .returnValue is not suitable to return complex results like ILIST colelctions. By the way if you stress on using this method, take a look ad window.opener and window.returnValue properties at MSDN.

Anyway, lets go back to our code. For btnOk button we don’t assign a JavaScript code to it because we have to calculate somethings and put it in session variable before the pop-up window is closed. Therefore, in the code behind and in OnClick event of btnOk button write a code like this:

// GatherAllSelected is a method to get selected items. You can write any similar function to do this.

IList<string> Result = GatherAllSelected();

// we put the list into Session object
if (Session[“Selected”] != null)
Session[“Selected”] = Result;
else
Session.Add(“Selected”, Result);

// a code to be run in client-side
string scriptStr = “<script>window.close();</script>”;

// send the script to output stream
ClientScript.RegisterClientScriptBlock(typeof(string), “closing”, scriptStr);

What does the above code do for us? First, a method named GatherAllSelected prepares the value to be returned. You can write your own method with any return type. Then, we put the result value into Session object. If we decided to user window.returnValue we could not return complex results unless we serialized them. That would be a hell indeed.

At the end we have to close the the pop-up window. Since the client-side code of a Button is always executed before the server-side code we can not write window.close(); in btnOK’s OnClientClick property. Instead, we generate a small JavaScript code , and send it to client by ClientScript.RegisterClientScriptBlock method. This will make our script run and consequently close the dialog.

After the dialog is closed, the OnClick event of our called button (btnOpenDialog) is called. In it, we can retrieve our expected value from Session object and use it:

protected void btnOpenDialog_Click(object sender, EventArgs e)
{
if (Session[“Selected”] != null && Session[“Selected”].ToString() != “”)
{
lblResult.Text = “”;
IList<string> Result = Session[“Selected”] as IList<string>;
foreach (string item in Result)
lblResult.Text += item + “\n”;
Session[“Selected”] = “”;
}
}

Important note:

If you run the above example, when you click on btnOK button (on child.aspx) nothing will happen! Even, if you do something that posts back your page, a new window will be opened!

How to solve it?

To sort this problem out simply put the following line in the child.aspx’s HEAD section:

<base target=”_self”/>

This code will make the new page open in the same window.

How to pass initial values to the pop-up window?

For this we can use Request.QueryString property but we also need to change our method a little bit. In Child.aspx and at Page_Load even handler, check the QueryString property and retrieve your initial values. The following sample code is doing it:

if (!IsPostBack)
{
string SelectedList = “”;
if (Request.QueryString[“Selected”] != null)
SelectedList = Request.QueryString[“Selected”];
string[] items = SelectedList.Split(‘,’);
foreach (string item in items)
clbFruit.Items.FindByValue(item).Selected = true;
}

This code assumes that the initial values are seperated by commas. So it will split them into a string[] array and use them in a proper way.

If your initial values are not constant and they are calculated in your code behind, you will have to remove the OpenDialog() method from caller.aspx page. You also must remove the value of btnOpenDialog.OnClientClick property. Otherwise you will get a script error whenever this button is clicked.

After removing these values, write a code like this in caller.apx’s Form_Load event:

if (!IsPostBack)

{

string ScriptBody=‘Child.aspx?InitialValues={0}’;

:

:

}

Then calculate your initial values and shape them in a comma separated string (i.e. ‘Banan,Apple’). Afterwards, format ScriptBody variable to include your initial value string:

ScriptBody = String.Format(ScriptBody , ‘Banana,Apple’);

Well, now you must send a window.showModalDialog or window.Open command yo the client. This approach is good also because in your code behind you can simply detect the browser type and change your script code easily to be compatible with Firefox or IE.

Anyway, again send your script to client by ClientScript.RegisterClientScriptBlock method:

string FinalScript = “<script> window.showModalDialog( “+ ScriptBody + “, ” ,’center:yes;resizable:yes;status:no;dialogWidth:3030px;dialogHight:200px’);</script> “;

ClientScript.RegisterClientScriptBlock(typeof(string), “closing”, FinalScript );

That’s it! You can download my sample code HERE and see how it works.

Thanks,

Aref Karimi


Advertisements

18 thoughts on “How to open popup windows in IE/Firefox and return values using ASP.NET

  1. Vikas says:

    Excellent!!!. On small question. I find that diffferent third party controls have actually implemented desktop like applications. I feel that they also open different types of dialogs only. Also they use diferent icons for minimise, expand, close for these dialogs. Can u please throw some light on this.

  2. borhan says:

    hi,

    Thank you for the code. but I have another question. I was wondering if you know how to bring up multiple popup windows at the same time .

    I am trying to click on one link on a webform in asp.net. and using that one link get three popups.

    I can manage to get them up once at a time, so once i close one the other popup opens.
    —————–

    Hi Borhan,
    If a window is modal you can not work on other windows. Actually this is the definition of a modal window! If you want to be able to switch between multiple windows, you may better use window.Open method.
    However you may find the following discussion in forums.asp.net website useful:
    http://forums.asp.net/p/1165760/1938502.aspx#1938502

  3. borhan says:

    Thank you, I was able to figure that out.

    But i also have another question.

    I used frameset to call three ip addresses, Two that are cameras(I put their ip addresses in webforms) and one that is a software. I cant use framesets properly for the cameras because it has been written in asp.net and it has a log on page. Once you log on the page takes up the whole screen. so basically im going around it by using popups.

    anyways, for the cameras i made webforms, that read the ip addresses assigned by doing this:
    Page.ClientScript.RegisterStartupScript(this.GetType(), “openWindow”, “window.open(‘http://66.212.162.84/’,’window1′,’left=5, top=585, Width= 405,Height= 357, status=no, resizable= yes, scrollbars= yes,alwaysRaised= yes, toolbar= no,location= no, menubar= no’)”, true); //which will bring up the page automatically.

    Now, How can i Make the popups stick to the asp.net frameset that i made, so that when you click on other places on the screen the popups dont go behind the page frameset page.

    Thank you for your time,

    Borhan

    Hi,
    As far as I remember, there is a parameter for window.Open method, named z-order . If you set that parameter to a big number (i.e. 1000), the window will be stayed on top.

  4. Murali says:

    unlike the showModalDialog() in IE, I cannot restrict the user to access the parent page when the popup is opened in Firefox. i want the javascript code for restricting the user in firefox also

  5. Murali says:

    hi,

    In javascript for confirmation message, I’m getting ok and cancel in popup, intead of that one i want yes or no buttons. Is there any code in javascript that display yes or no buttons?

    Hi,
    Don’t think so. instead you can use ModalPopupExtender (a control of Asp.net ajax). Please refer to a post about client-side messages in my blog.

  6. Ganesh Pai M V says:

    Hi,

    I tried out this code. It doesn’t work for me. 😦

    I have Ajax .Net components in my pages. Will this hinder this approach?

    I want to close the modal window after I execute some server-side calculations, when the OK button is clicked.

    Thanks a lot

    Ganesh Pai M V

    • aspguy says:

      Hi, sorry for late reply.
      If you are using Ajax components, I recommend you to use modalPopupExtender control that is a part of Ajax Control Toolkit.

  7. فرشته says:

    مرسی
    عالی بود
    کلی سرچ کرده بودم ولی هیچ کدوم به کاملی این نبود،مشکلم حل شد

    • سلام فرشته جان
      از کجا فهمیدی که این وبلاگ ایرانیه؟ از اینکه کامنت فارسی گذاشتی تعجب کردم
      🙂

  8. hi,

    i have lot of checkbox record in child page,so i used gridview with pageing in child page,then i click paging in chcild page the new page opening????

    how to solve this????
    very urgent

  9. Use Jquery Colorbox, this will allow u to open the popup page in iframe which look like modal popup with a bit of css and can easily pass values using some hidden fields on parentpage and use parent.getelementbyid to set those values and access it onclose event of colorbox, without and postback and then raise button click event of any hidden button to perform any serverside use.

    i use this method and its cool

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s