Thursday, January 6, 2011

Open new window with Response.Redirect() in Asp.net- 2nd part

In my previous post I show you how to open a new window in asp.net using "aspnetForm.target".

Second approach(Using ResponseHelper class)

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);
        }
    }
}


Now you can just call ResponseHelper.Redirect, first parameter is desired "url", second parameter is for specify a target to be "_self" or "_blank" and third parameter is "windowFeatures" by which you can specify whether the new window should have a menu bar, and what its width and height are.

Disclaimers:

Note: 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.

Note: Beware of popup blockers.

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

No comments:

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...