adsense

Saturday, March 22, 2014

Redirect to new window using Reponse.Redirect

We all know that we can use JavaScript's window.open method to open a new window.  I was curious if there is to achieve this from the code behind.  The answer is you can and there are various ways you can use depending on the requirement.

I did it by using writing an extension method  to Reponse.Redirect as shown below.
public static class ResponseHelper
{ 
public static void Redirect(this HttpResponse response, 
string url, string target, string windowFeatures) 
    { 

        if ((String.IsNullOrEmpty(target) || 
target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && 
String.IsNullOrEmpty(windowFeatures)) 
        { 
            response.Redirect(url); 
        } 
        else 
        { 
            Page page = (Page)HttpContext.Current.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); 
        } }
 }

usage
Response.Redirect(redirectURL, "_blank", 
"menubar=0,scrollbars=1,width=780,height=900,top=10");
This has been originally suggested in the following post. The post dscusses various ways you can achieve the same functionality.
http://stackoverflow.com/questions/104601/response-redirect-to-new-window
 Cheers
Samitha

No comments:

Post a Comment