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).

Comments

  1. The code written by you may be correct but it'z not working on Asp.Net 1.1 so I request you to please mention da requirement in your future blogs.


    Cheers,
    Gangor Creations(http://gangor-creations.tripod.com/)

    ReplyDelete
  2. It's not working


    Just tell me is there any name space whick i have to call to use this helper class

    ReplyDelete
  3. t's not working


    Just tell me is there any name space whick i have to call to use this helper class

    ReplyDelete
  4. @Alok,

    There was a typo in the code. Now I have posted more formatted code of ResponseHelper class and examples of calling this class from the web form. I have also provided a link to download the source code. Hope this will be helpful to you.

    ReplyDelete
  5. how to redict to previous caling page in c#

    ReplyDelete
  6. @sirisha,

    I can't understand what you mean by previous calling page. If you mean to open the previous page in the new window, you can use the same code. You will get the url of the previous page from the HTTP_REFERRER server variable. pass this url as argument to the redirect method of the response helper class.

    ReplyDelete
  7. Great job!
    Just what I was looking for.

    Thanks for your hard work...

    ReplyDelete
  8. Dear Yanesh

    I am trying to built an application that will do the following:

    after having executed a sql query and having the results in Page1.aspx (for example) i want to be able to hit on a result (for example to a client name) and be able to be redirected to another page,that will have some questions for the client to be completed and saved to a database. so i will want these answers to be saved to his "file"lets say.

    can you give me some base code directions that does smt like this?

    thank you so much

    please email me at papadopoulosvasileios@gmail.com

    ReplyDelete
  9. Jaume Pujol-BusquetsMonday, 21 September, 2009

    Thanks very much! It has helped me a lot!

    ASP NET is an architecture in which simple things are meant to be done the difficult way...

    Anyway, thanks again!!!

    ReplyDelete
  10. Uhm, you do actually realise this just writes JavaScript to the client and then preformes a window.open(). Something you said was "totally unacceptable".

    ReplyDelete
  11. It works. Thanks for the post. It's a pitty that it doesn't go past the pop-up blockers though.

    ReplyDelete
  12. You're a genius!

    ReplyDelete
  13. DUDE YOUR A GENIUS!!!

    ReplyDelete
  14. Doesn't work for IE. Any suggestion?

    ReplyDelete
  15. its not working!!!!!!!!!!!

    ReplyDelete

Post a Comment

Popular posts from this blog

CBSE Class X Result 2010 – How to Calculate Percentage

Shatrughna Temple, Rishikesh