Thursday 1 July, 2010

Response.Redirect open new window

Sometimes we need a button action or something during the postback to pop open a new window / tab using the very known Response.Redirect. This is easy to do, simply add OnClientClick="aspnetForm.target ='_blank';" in the button's property.

So I came across the day the desire to have a button open up a new window instead of just using an anchor tag, as usual I run the idea through google and mostly come back with responses saying it’s not possible that way, or to add javascript to the page to capture events. Not quite the solution I was looking for after doing some more searching I came across a javascript solution that would work but wasn’t elegant at all which led me to ponder on adapting it to be cleaner and this is what I came up with.

  protected void btnNewEntry_Click(object sender, EventArgs e) {     Response.Redirect("New.aspx"); } 

It even works using Server.Transfer. There you have it a simple unobtrusive solution to handle Response.Redirect into a new window without needing to add any javascript tags and only take advantage of the OnClientClick event on the button itself.

Update 10/22/2008:

I’d like to thank one of my commenters, Dan, for his solution for accessing the form inside a master page on the child page level.

Button1.OnClientClick=string.Format(”{0}.target=’_blank’;”,   ((HtmlForm)Page.Master.FindControl(”form1″)).ClientID); 

This code will dig down into the controls collection and find your form and allow you to get access to the client id so you can be sure you have proper naming of it for the javascript to function correctly. Make sure you replace “form1″ with whatever you have your parent form id=”name” set to inside your Master’s page markup.

Update 11/04/2008:

If you have multiple buttons on a single page and only want a specific button to launch into a new windows and want the rest to stay on the current form make sure you decorate your other buttons like

  protected void btnStayOnPage_Click(object sender, EventArgs e) {    //Do normal code for postback } 

BloggingContext.ApplicationInstance.CompleteRequest();

No comments:

Post a Comment