ASP.Net Code, JavaScript Code

Open a New Browser Window From an ASP.Net Server Control

All ASP.Net controls add functionality to your web application by performing postbacks to the server. When they post back, their events are captured by the web server. So if you add an onclick event to a button, it will be a server-side event. But what if you need a button to open a window or JavaScript prompt when you click on it? This is a client-side event, and there's no way to add this property to an ASP.Net server control it would seem. Here's the code to allow you to do it programmatically.

Basically, we have to alter the HTML output of the button before the page loads or renders. The easiest way to do this is to add an attribute to the web control. So so we had a button control that looked like this:


<form runat="server" id="form1">
   <asp:button id="button1" runat="server" onClick="button1_click" />
</form>

The "button1_click" event refers to a method that is run on the server. Here's how to add the JavaScript to create a popup, popunder, alert, or whatever else you need to do on the client side:


void page_load(object s, EventArgs e)
{
    if (!IsPostBack)
    {
       button1.Attributes.Add("onclick", "window.open('help.htm', '', '', 'height=200,width=400'");
       // or alert user
       //button1.Attributes.Add("onclick", "alert('You clicked the button')");
       // or whatever
       //button1.Attributes.Add("onclick", "anyJavaScriptFunction");
    }
}
Share

6 Comments

  1. i want to open window on client machine on button click of main page
    let the client select some data from that window
    set the selected data to controls on main page
    and then i want execute some server code

    server code must be excuted after whole client code is executed

  2. I don't really understand what you're asking

  3. why not just do this in a button_click()?

    HyperLink1.Target = "_blank";
    HyperLink1.ResolveClientUrl("http://www.cnn.com");

    it's a piece of cake!

  4. Thank you good fellow

    Not only giving a nice solution, but explaining the cause of the problems when trying to do it with pure asp.net.

    You made my day end happy! wish the same for you every day

  5. Thanks for the way. Here goes how to open new window in asp.net using javascript: http://dotnetspidor.blogspot.com/2009/01/open-new-window-in-aspnet-web-page_28.html

    Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image