Tuesday, October 09, 2007

Redirecting to new window in c#

As a developer, many time I wished to redirect user to a new URL into a new browser window. I wanted to use response.redirect at server side and open the new web page into a new window. But the way redirection works makes it impossible to open a new window from server side. The common solution to this problem is to use java script's window.open statement at client side and then fetch the new URL into the new window. To me, this is totally unacceptable while I am writing server side code. So I decided to write some code to do this. But before writing, I googled for the same. I found a good solution for the problem. I would like to give proper credit to the author, who chose not to publish his/her name. As they say a code worth one thousand words, here is the code:

ResponseHelper Class:

The ResponseHelper class does all the magic. It adds a client side script to the response which opens the new window. Use this class in place of response class if you want to open new window. You may create a new class in App_Code folder with name ResponseHelper.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

/// <summary>
///
ResponseHelper Class provides static methos Redirect
/// which opens new browser window.
/// </summary>
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);
}
}
}

Using Response Helper Class:

ResponseHelper class’ static Redirect method is used to redirect into new window.
ResponseHelper.Redirect("default.aspx", "_blank", null);

The Redirect method accepts thee parameters:

  1. Redirection URL: The URl which will be opened into the new window.
  2. Target Frame: 
    1. Use “_Self”, if you don’t want to open new window. Null means “_Self”.
    2. Use “_Blank” to open into new window.
  3. Window Feature: Window features can be added like width, height, scrolling etc. using this parameter.

Example of Using Response Helper Class

I created a page default.aspx. This page has a link button lbtn1. In the OnClick event of this link button, I opened another page Page2.aspx in new window.

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Redirect to New Window in C# Example</title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
Click on the button below to open new window.<br />

<
asp:LinkButton ID="lbtnRedirect"
Text="Open New Window"
OnClick="lbtnRedirect_Click"
runat="server">
</
asp:LinkButton><br />
</
div>
</
form>
</
body>
</
html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void lbtnRedirect_Click(object sender, EventArgs e)
{
ResponseHelper.Redirect("page2.aspx", "blank", null);
}
}

Notes:

  1. If you use it outside the context of a Page request, you can't redirect to a new window. The reason is the need to call the ResolveClientUrl method on Page, which I can't do if there is no Page. I could have just built my own version of that method, but it's more involved than you might think to do it right. So if you need to use this from an HttpHandler other than a Page, you are on your own.

  2. Beware of popup blockers. New window is a popup. So it will not work if popup is blocked.

  3. Obviously when you are redirecting to a new window, the current window will still be hanging around. Normally redirects abort the current request -- no further processing occurs. But for these redirects, processing continues, since we still have to serve the response for the current window (which also happens to contain the script to open the new window, so it is important that it completes).

Download Source code of this article (5kb in zip format).

Related Posts

There was an error in this gadget