Redirecting to new window in c#
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:
- Redirection URL: The URl which will be opened into the new window.
- Target Frame:
- Use “_Self”, if you don’t want to open new window. Null means “_Self”.
- Use “_Blank” to open into new window.
- 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:
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.
-
Beware of popup blockers. New window is a popup. So it will not work if popup is blocked.
-
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).
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.
ReplyDeleteCheers,
Gangor Creations(http://gangor-creations.tripod.com/)
It's not working
ReplyDeleteJust tell me is there any name space whick i have to call to use this helper class
t's not working
ReplyDeleteJust tell me is there any name space whick i have to call to use this helper class
@Alok,
ReplyDeleteThere 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.
how to redict to previous caling page in c#
ReplyDelete@sirisha,
ReplyDeleteI 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.
Great job!
ReplyDeleteJust what I was looking for.
Thanks for your hard work...
Dear Yanesh
ReplyDeleteI 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
Thanks very much! It has helped me a lot!
ReplyDeleteASP NET is an architecture in which simple things are meant to be done the difficult way...
Anyway, thanks again!!!
Uhm, you do actually realise this just writes JavaScript to the client and then preformes a window.open(). Something you said was "totally unacceptable".
ReplyDeleteIt works. Thanks for the post. It's a pitty that it doesn't go past the pop-up blockers though.
ReplyDeleteYou're a genius!
ReplyDeleteDUDE YOUR A GENIUS!!!
ReplyDeleteDoesn't work for IE. Any suggestion?
ReplyDeleteits not working!!!!!!!!!!!
ReplyDeleteThank you sooo much!!!!!!
ReplyDelete