Wednesday, January 27, 2010

Javascript Window.Open() in .NET

Here's an example on how to popup a new window using javascript in .NET. First we'll use a simple button as the trigger source for the popup.

<asp:Button ID="btnPopup" runat="server" />

Then on the page load in the code behind, add an onclick attribute to the button.

protected void Page_Load(object sender, EventArgs e)
{
    btnPopup.Attributes.Add("onclick", "window.open('http://" + Page.Request.Url.Authority + "/TestPage.aspx','Test','status,toolbar,location,menubar,directories,resizable,scrollbars,width=400,height=400')");
}
 
The Page.Request.Url.Authority in the code above will retrieve the root url of your site. Then just add the name of the aspx file to popup after the forward slash (if it is within another directory, just add the directory name before the aspx file, and so forth).
 
To explain the javascript part, window.open() accepts 3 parameters: the url of the site to popup, the window name (not title, the title should be in the head part of the new page, so make sure it doesn't have spaces), and window features.
 
Here's some of the commonly used window features:
 
status:
 

   
toolbar:


 
location:


 
menubar:


 
directories:


 
resizable: window can be resized


 
scrollbars:


 
width: the width of the window in pixels
 
height: the height of the window in pixels



To use these features simply add them to the list like this:

"window.open
('http://www.testpage.com','Test','status,toolbar,location,menubar,directories,resizable,scrollbars,width=400,height=400')"




If not then simply omit them:

"window.open('http://www.testpage.com','Test','width=400,height=400')"





That's it, one note though, make sure that the aspx page in the url exists or you'll get an error.



-k

1 comment: