Opening popup windows with ASP.NET

One of the most asked question on the asp.net newsgroups is, "How can i open a popup window with ASP.NET?". The short answer is, "You can't.". Opening popups is a client side task that requires Javascript. But you can have ASP.NET emit Javascript to the client.

Most if not all of the server controls in ASP.NET have an Attributes.Add method that allows you to add custom attributes to the server controls. For example, you can add a client side onclick event to a hyperlink control or an onload event to a body tag. The Attributes.Add method takes 2 arguments, the first is a key which in the case of adding javascript, will be onclick, onload or other event and the second argument is the value which can also be a string or even a variable.
Make 2 new pages - default.aspx and popup.aspx. Add some text to popup.aspx. Next, add a hyperlink control to default.aspx and set its NavigateUrl property to javascript:;. Add the following code to the Page_Load subroutine.

Hyperlink1.Attributes.Add("onclick", "window.open('popup.aspx',null,'height=250, width=250,status= no, resizable= no, scrollbars=no, toolbar=no,location=no,menubar=no ');")

Preview default.aspx in your browser and when you click the hyperlink, a new popup window will open.

Opening a popup from a hyperlink is fine but what if you need it opened when the main page loads. Thats easy to do. First you need to add runat="server" to the body tag in default.aspx, and give it an ID of bodytag. If you are using codebehind, you'll need to declare the body tag as follows.

Protected WithEvents bodytag As HtmlGenericControl

If you are using the inline script model, you shouldnt have to declare it. The next step is add the onload event to the body tag as follows. Again it goes in the Page_Load subroutine.

bodytag.Attributes.Add("onload", "window.open('popup.aspx',null,'height=250, width=250,status= no, resizable= no, scrollbars=no, toolbar=no,location=no,menubar=no ');")

Preview the page and your popup will open when the page loads
Using the Attributes.Add method lets you add javascript events to any of the server controls. You can even specify a function name for the value parameter.

************************************************************

We can access the values from one page to another page by means of the following code.
In the First Page just add the following code,

Context.Items("first_name") = txtfirstname.Text

In the Second page just use the following code,

Dim name as String = CType(Context.Items("first_name"), String)

You will obtain the value in the Second Page now.

No comments: