Wednesday, August 27, 2008

How to: Open a new window using Response.Redirect

In short - it is not possible - at least not directly. The reason is that Response.Redirect is code that runs server side. And the server does not know anything about the client's windows or frames. Hence you cannot do a Response.Redirect and have it open a new window.Open-new-window

Having said that - there are other ways in which one can accomplish this objective. One can do this by using JavaScript. One can inject javascript into the Response.Redirect method, but I found this unreliable and it did not always parse the URL correctly.

Here is an easier way to do it - using the Response.Write method.

In the code-behind file and in the method from which you wish to spawn a new window - add the following code: (C#)

private void OpenNewWindow(string url, string windowName, string windowParams)
    {
        if (url == null)
            throw new ArgumentNullException("url");
        if (windowName == null)
            windowName = "";
        if (windowParams == null)
            windowParams = "";
        string scriptCode =
            string.Format(
                "<script>window.open('{0}','{1}','{2}');</script>",
                url, windowName, windowParams);
        //write the script out to HTTP Response stream
        Response.Write(scriptCode);
    }

And call it in this manner:

protected void Button1_Click(object sender, EventArgs e)
    {
        const string url = "default.aspx";
        //name of window - leave blank to open each url in a new window
        //use a name to reuse the window
        const string windowName = "";
        //params for a window
        //these params open the url in a popup style window (no toolbar, status bar, etc)
        const string windowParams = "height=760,width=760,status=yes,toolbar=no,menubar=no,location=no,resizable,name=Notes";
        
        OpenNewWindow(url, windowName, windowParams);
    }

2 comments:

Anonymous said...

When you assign abolute path to url (~/test1/NewWindowPage.aspx), it still includes the current page(abc.aspx) and concatenates the path to the existing page and produces (/abc.aspx/(~/test1/NewWindowPage.aspx).

Raj M. Rao said...

In the above case you can use Page.ResolveUrl to convert a rooted path to an absolute path.