Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Response.Redirect into a new window

4.94/5 (16 votes)
23 Jan 2012CPOL1 min read 181.8K  
Response.Redirect into a new window
The only way to open a new window is for it to be initiated on the client side, whether it be through script or clicking on a link.

So the solution always proposed to this problem is to instead write out some script that opens the window, rather than using Response.Redirect:
JavaScript
<script type="text/javascript">
    window.open("foo.aspx");
</script>

Now the helper method which is used for redirecting to new page.

It's easy enough to write a little helper that abstracts the details away from us... while we're at it, we might as well add target and windowFeatures parameters. If we're going to open the new window with script, why not let you use all of the window.open parameters? For example, with windowFeatures you can specify whether the new window should have a menu bar, and what its width and height are.
C#
    public static class ResponseHelper {
    public static void Redirect(string url, string target, string windowFeatures) {
        HttpContext context = HttpContext.Current;
 
        if ((String.IsNullOrEmpty(target) ||
            target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&
            String.IsNullOrEmpty(windowFeatures)) {
 
            context.Response.Redirect(url);
        }
        else {
            Page page = (Page)context.Handler;
            if (page == null) {
                throw new InvalidOperationException(
                    "Cannot redirect to new window outside Page context.");
            }
            url = page.ResolveClientUrl(url);
 
            string script;
            if (!String.IsNullOrEmpty(windowFeatures)) {
                script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
            }
            else {
                script = @"window.open(""{0}"", ""{1}"");";
            }
 
            script = String.Format(script, url, target, windowFeatures);
            ScriptManager.RegisterStartupScript(page,
                typeof(Page),
                "Redirect",
                script,
                true);
        }
    }
}

Now you just call ResponseHelper.Redirect, and it figures out how to honor your wishes. If you don't specify a target or you specify the target to be "_self", then you must mean to redirect within the current window, so a regular Response.Redirect occurs. If you specify a different target, like "_blank", or if you specify window features, then you want to redirect to a new window, and we write out the appropriate script.
C#
ResponseHelper.Redirect("popup.aspx", "_blank", "menubar=0,width=100,height=100");

If there is any query for understanding this, then let me know.
Thank you.
@ChetanV@

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)