Thursday, December 20, 2007

First Post and First Problem

How do you code to open a new window when a button is clicked? If you use HTML or server side scripting like ASP, it's pretty simple, because you only need to call a javascript function window.open(...) in the button's onclick event. Thing gets a bit more complicated if you code using ASP.Net, which I experienced lately. In my case, I want the popup window to display a particular page according to selected value of a dropdownlist.

So, after doing some little research in Google, I tried to use Response.Write() method and put "<script>window.open(...)</script>" as its param. The Response.Write () was called inside the OnClick event handler of the button.
Note: I was using code behind class.
Since the popup page should be dependent on the selected value of a dropdownlist, so I used a switch-case statement to determine which page I should open. Actually it worked, but there was a small thing that bother me. After I clicked the button a popup window was displayed, and the main page was also refreshed. This refresh made the layout of the main page in a mess.

Then, I tried to use another method, that was ClientScript.RegisterStartupScript() and used window.open function as one of its param. This method worked perfectly fine for me. A popup window was displayed and the main page was still refreshed (of course!) but didn't ruin the layout.

"<script>window.open(...)</script>"I guess it was because the difference of where ASP.Net put javascript function in the page. Using the first way, the javascript function is printed on the very first line of the HTML code, while the second way, it prints javascript function inside "body" tag after the button tag.

1 comment:

yenny said...

hi, you can add onclick attribute to the button from code behind.
i put on the page load most of the time.

button1.attribute.add("onClick","functionName");

once the button clicked, it will call javascript function "functionName"

dont forget to return false inside the function, if u dont want to submit/refresh the page.

so.. for ur case, just to open a window.. no need postback :)

hope it will help :)