18 octobre 2007

Response.Redirect into a new Window

It is "not possible" to redirect into a new window, because a redirect on the server causes a special HTTP response to be sent to the users browser, the client. The browsers native implementation interprets the special response code and sends the user off to the destination. 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:



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
{
System.Web.UI.Page page = (System.Web.UI.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(System.Web.UI.Page), "Redirect", script, true);
}
}



Than, use this method like:

Redirect("MyPage.aspx", "_blank", "status=no,toolbar=no,menubar=no,location=no,resizable=yes,titlebar=no");

Aucun commentaire: