June 12, 2017

Open New Window from Server Side in ASP.Net using C#

Here Is the question I received from one of my colleagues, how to open new page from server side in a new window. There could be two possible ways to get it work.

  • First option is to add javascript code to the button's OnClientClick handler. But this handler should be attached before the control is rendered, let's say in button's OnPreRender event.

    protected void MyButton_OnPreRender(object sender, EventArgs e)
    {
        string newPageUrl = "NewPage.aspx";
        MyButton.OnClientClick = "window.open('" + newPageUrl + "'); return false;";
    }
    

    This technique would not let the request post back to the server, so it could save this round-trip.

  • Second option could be use of Response.Write() method on regular button click event.

       Response.Write("<script>window.open('http://www.google.com.hk/','_blank');</script>"); 
    

    This would send a post back to the server, but the advantage to this method could be that it will allow you write code on button click you may want to execute before opening a new window.

No comments:

Post a Comment