7.5 Show a Pop-Up Window with JavaScript


Problem

You need to show a secondary (pop-up) window, perhaps in response to a user action.

Solution

Register a JavaScript function (or add a control event attribute) that uses the window. open JavaScript function.

Discussion

Because all ASP.NET code executes on the server, there is no way to show a new window from your C# page code. You can add URL hyperlinks to a page that will automatically open in a new window by setting the target attribute of the anchor tag to _blank , but this still doesn't give you the ability to control the window size or style.

The solution is to use client-side JavaScript code to open the secondary window. The secondary window itself could be an HTML page, an ASP.NET page, an image file, or any other type of resource that can be opened in the client's browser. To open a secondary window, you use the window.open function and specify three parameters. The first parameter is the link for the new page, the second is the frame name of the window, and the third is a comma- separated string of attributes that configure the style and size of the pop-up window. These attributes can include the following:

  • The height and width attributes, which are set to pixel values.

  • The toolbar , menuBar , and scrollbars attributes, which can be set to yes or no depending on whether you want to display these elements.

  • The resizable attribute, which can be set to yes or no depending on whether you want a fixed or resizable window border.

The following example shows how you can configure an ASP.NET Button so that it opens a second ASP.NET page in a pop-up window when clicked. Typically, you would add this code to the Page.Load event handler.

 string popupScript = "window.open('PopUp.aspx', " +   "'CustomPopUp', " +   "'width=200, height=200, menubar=yes, resizable=no')"; cmdPopUp.Attributes.Add("onClick", popupScript); 

Here's the code you would use to show a pop-up window automatically when the page is displayed. This code would also go in the Page.Load event handler.

 string popupScript = "<script language='javascript'>" +   "window.open('PopUp.aspx', " +   "'CustomPopUp', " +   "'width=200, height=200, menubar=yes, resizable=no')" +   "</script>"; Page.RegisterStartupScript("PopupScript", popupScript); 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net