C# ASP.NET Response.Redirect Open Into New Window

UPDATED: 11/04/2008 (see bottom of post)

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.

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"

OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>

protected void btnNewEntry_Click(object sender, EventArgs e)

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.



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

<asp:Button ID="btnStayOnPage" runat="Server" CssClass="button" Text="Stay here"

OnClick="btnStayOnPage_Click" OnClientClick="aspnetForm.target ='_self';"/>

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


kick it on DotNetKicks.com

96 thoughts on “C# ASP.NET Response.Redirect Open Into New Window

  1. I have a Link button on my page with PostBackURL set to a page called PX.aspx. I have set the OnClientClick to aspnetForm.target=’_blank’, but my page does not open in a new window. Is there anything else i should look out for.


  2. Take a look at the source html on your page and make sure the form name is actually aspnetForm and not a different id.

  3. Chris I have a doubt.
    Actually i am passing paramter from one page to another to display report. If user does not sends a valid paramter the window should close informing the user of the error. My Code is

    MessageBox.Show(“Please select the component to view report”, “Report Data”, MessageBoxButtons.OK, MessageBoxIcon.Error);

    but i find that it opens two windows instaed of single window in case of user not selecting a valid paramter. can u suggest me on this.

    Thanks for the help earlier.

  4. Hi Chris,
    This is happening because of auto postback property of a dropdown list control as i am using that. But i need to display report based on multiple conditions and each condition depends upon the previous one. Eg.
    Base control holds all the base name.
    Depending upon base, location names are listed.
    Depending upon Location Dept names are to displayed. etc.

    Here each time the user selects invalid value a window opens upon postback. how can i overcome this.

    My code is written upon button click

    if (ddlBase.SelectedIndex == 0)
    lblMessage.Text = “Select the Base”;
    MessageBox.Show(“Select The Base”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    else if (ddlLocation.SelectedIndex == 0)
    lblMessage.Visible = true;
    lblMessage.Text = “Select the Location”;
    MessageBox.Show(“Select The Location”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    else if (ddlDepartment.SelectedIndex == 0)
    lblMessage.Visible = true;
    lblMessage.Text = “Select the Department”;
    MessageBox.Show(“Select The Department”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    else if (ddlComponent.SelectedIndex == 0)
    lblMessage.Visible = true;
    lblMessage.Text = “Select the Component”;
    MessageBox.Show(“Select The Component”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    string strComponet = string.Empty;
    string strDeptName = string.Empty;
    string strLocName = string.Empty;

    strComponet = ddlComponent.SelectedValue;
    strDeptName = ddlDepartment.SelectedValue;
    strLocName = ddlLocation.SelectedValue;

    Response.Redirect(“ConditionalReport.aspx?Component=” + strComponet + “&Dept=” + strDeptName + “&Loc=” + strLocName);


    and on client click

    OnClientClick=”aspnetForm.target =’_blank’;”

    I will be obliged if you can help me.

    Thanks for your efforts and help

  5. What I’d recommend is checking the drop down list for a similar event to OnClientClick probably OnSelectedIndexChanged if your using the built in dropdownlist web control and set on that method

    OnSelectedIndexChanged=”aspnetForm.target =’_self’;”

    This should reset the form target for the drop down list changes that it will post those to the current window and only open the new window when you click the button instead of causing all your posts back to open in a new window. My other suggestion would be if that doesn’t solve it is to take off auto post back on the dropdownlist and set the logic that you have in the change event to be ran inside the button click method instead and have it do it’s validation/selection operations there.

  6. Hi Chris,
    Can u suggest me on this:
    I need to generate a text file with some data in it. which is working fine for me.
    My question is,
    how can i save the text file on the client’s hard drive instead of saving it on the server.

    Thanks For the Help and suggestion

  7. Pankaj,

    Basically what you want to do is when they click the link to download the text file to redirect them to an aspx page that is basically entirely blank similar to

    In the code behind you will need to handle getting the data to display the text file then to render it out to the window do something similar to

    byte[] _content = txtDocumentBinary;

    Response.Buffer = false;
    Response.ContentType = “application/octet-stream”; Response.AddHeader(“Content-Disposition”, string.Concat(“inline; filename=”, _fileName,”.txt”));
    Response.AddHeader(“accept-ranges”, “bytes”);
    Response.AddHeader(“Content-Length”, _content.Length.ToString());
    Response.OutputStream.Write(_content, 0, _content.Length);

  8. In a datagrid an entire column is of LinkButton type.
    As you mentioned, I have added the property onclientclick

    <asp:LinkButton ID=”LinkButton1″ runat=”server”
    CommandArgument=” CommandName=”event_id_link”
    onclientclick=”aspnetForm.target=’_blank’;” >

    In my RowCommand event of the Gridview, code goes as

    Response.Redirect(“~/CRM/et.aspx?event_id=” + Session[“EventID”].ToString());

    Regardless does not open a new page with details.
    Am I doing anything wrong, any suggestions will be helpful

    Thanks in advance

  9. SP

    I believe this is an issue of browser interpretation of Link Buttons. Link buttons aren’t true buttons they are just anchor tags with hrefs. I do not believe link buttons have an OnClick which is what OnClientClick will become when it is rendered out. I believe in internet explore it will acknowledge the OnClick event even though it’s invalid but browsers that follow HTML specifications correctly will ignore it.

    Try switching this over to a regular button and see if it works, also double check your pages actual source in the browser to verify that the form id is actually named “aspnetForm” and not assigned another value.

  10. Thanks Chris,
    I am using Message Box in my asp.net application (asp.net version 2.0)
    The Syntax is :-

    MessageBox.Show(“No Matching Record Exists…”, “Information”, MessageBoxButtons.OK, MessageBoxIcon.Information);

    But i am getting a the following error mentioned below.

    Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

    Can you suggest me any solution on this.

    Thanks a lot chris, for helping me each time.
    I am obliged.


  11. Pankaj,

    MessageBox.Show is for windows forms applications only that’s why you’re getting that error message. The simplest way to acheive that is with the javascript Alert(“your message here”) method. Creating dialogs for web applications is an overly complex task for some reason.

    Take a look at this for a better solution than the javascript alert. http://weblogs.asp.net/johnkatsiotis/archive/2008/09/14/asp-net-messagebox-server-and-client.aspx

  12. Pankaj if you would rather it display as a save this file as dialog when they click the link change

    Response.AddHeader(”Content-Disposition”, string.Concat(”inline; filename=”, _fileName,”.txt”));


    Response.AddHeader(”Content-Disposition”, string.Concat(”attachment; filename=”, _fileName,”.txt”));

  13. Is there any way to control the size of this new window when we are using OnClientClick=”aspnetForm.target =’_blank’;”?

  14. That’s great to hear Bob!

    Shafiq, that I’m a little hesitant to say, I think you might be better off on the page that it pops up to have inside the new page javascript to resize the window to the size you want. I think that would be the best option.

  15. Hi Chris,
    when i am trying to access a report from client, it is giving me the following error.

    Can you please suggest me something for this. Do i need to make any changes in web.config file. I have implemented forms authentication.

    The Error is as follows:-

    Access to the path ‘D:\ReportsData\objdsShowData.xml’ is denied.

    Exception Details: System.UnauthorizedAccessException: Access to the path ‘D:\ReportsData\objdsShowData.xml’ is denied.
    To grant ASP.NET access to a file, right-click the file in Explorer, choose “Properties” and select the Security tab. Click “Add” to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

    Source Error:

    Line 37: strTableName = classInventory.GetTableName(strComponentName);
    Line 38: objdsShowData = classInventory.GetReportData(strTableName);
    Line 39: objdsShowData.WriteXml(“D:\\ReportsData\\objdsShowData.xml”);
    Line 40: rptDoc.Load(Server.MapPath(@”SystemsData.rpt”));
    Line 41: rptDoc.SetDataSource(objdsShowData.Tables[“Table”]);

    Source File: d:\Inventory\Report.aspx.cs Line: 39

    Thank You for sharing your knowledge all the way through. I am obliged.


  16. Pankaj,

    The error you are receiving is a windows security error. The ASP.NET user account does not have access to that folder. There are a few ways to solve this

    1. give the ASP.NET account privileges to read (and write if needed) to that folder.
    2. Move that folder inside virtual directory folder
    3. Set up WindowsImpersonation and use an account that has accessible privileges to that folder, one of my previous posts deals with the WindowsImpersonation that I wrote about my TaskScheduler.

  17. Hi Chris,
    I have one small doubt If i enable WindowsImpersonation will my forms authentication be changed to windows authentication.
    Actually i am new to this section. I have never face this before so i am confused.
    How do i give the necessary permissions.
    I have created virtual directory in the IIS. And my application is already under this folder in the IIS.

    Thanks a lot for guiding me.


  18. Pankaj,

    Take a look at http://www.asp.net/learn/whitepapers/denied-access-to-iis-directories/ the top portion of the article basically outlines the same problem you are facing, ASP.NET is trying to access a resource it doesn’t have permission to. Towards the end of the article it shows a walkthrough for adding ASP.NET’s windows account to permissions on a folder which is what you want to do either for your folder with the .XML file or just specifically on the .XML file if you will not create any new files in that directory and will only read from the .XML files.

    Keep in mind every folder you add permissions to for ASP.NET there’s another area that potentially could be exploited if the machine is attacked. Generally the risk is fairly low especially if you are only granting read/write access to individual files. I would very strongly recommend NEVER grant execute access for any folders to ASP.NET manually. The risk there could become very high.

    I hope that helps!

  19. Thanks a lot for the immense and much needed help Chris.
    I am really grateful to you.
    Hat’s Off to your knowledge.


  20. Hello Chris,
    I am trying this with a Crystal Reports Browser.
    No new window though. I have been looking for something this elegant to work but perhaps I am missing a key element?

    protected void LoadReport(object sender, EventArgs e)
    // This tries to find the report in the folder when you click open
    // The report should have the filename as the name of the folder it’s in with -parameters, -dynamic, etc on the end
    // This function will go through these filenames in order and redirect to the first it finds
    // If it doesn’t find any, it returns an error message to the description textbox
    Description.Text = “No report found!”;

    protected void FindReport(string filename)
    // Creates the filename from the folder name and the additional -parameters, etc extension
    string rname = ReportsBrowser.Items[ReportsBrowser.SelectedIndex].Text;
    string[] titles = rname.Split(SplitLbl.Text.ToCharArray());
    foreach (string t in titles)
    rname = t;
    string favdesc = “e:Protrak/WebApps/Reports/CrystalReports/” + ReportsBrowser.SelectedValue + “/” + rname + filename;
    if (File.Exists(ReportsBrowser.SelectedValue + “/” + Path.GetFileName(ReportsBrowser.SelectedValue) + filename) == true)
    // Loading a project from the reports browser
    Response.Redirect(“http://protrak/Reports/CrystalReports/” + ReportsBrowser.SelectedValue.Remove(0, 41) + “/” + Path.GetFileName(ReportsBrowser.SelectedValue) + filename);
    if (File.Exists(favdesc) == true)
    // Loading a project from the favorites
    Response.Redirect(“http://protrak/Reports/CrystalReports/” + ReportsBrowser.SelectedValue + “/” + rname + filename);
    // window.open(‘CommunitySummary.aspx?mystring=MyString’);


  21. form id=”reports” runat=”server”
    asp:Button ID=”LoadButton” runat=”server” Text=”Open Report” OnClick=”LoadReport” OnClientClick=”reports.target=’_blank’;”/

  22. @Chris

    When you click the button does it execute your code correctly and do a Response Redirect but transfer the page inside the current window?

    Also did you verify in the browser by going to view source that form id is actually reports and ASP.NET didn’t override it and replace it with another value?

    Do you have javascript enabled?

  23. @Pankaj

    I’m always glad to share my knowledge because I know there’s always so much more I don’t know yet and the only way to grow as a developer is share your knowledge and learn from others.

  24. Thanks for the response Chris, it looks like I do according to the source:

    form name=”reports” method=”post” action=”Reports.aspx” id=”reports”

    script type=”text/javascript”>


  25. script type=”text/javascript”

    var theForm = document.forms[‘reports’];
    if (!theForm) {
    theForm = document.reports;
    function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    theForm.__EVENTTARGET.value = eventTarget;
    theForm.__EVENTARGUMENT.value = eventArgument;


  26. Something odd and I am not sure which character it is but the line containing the reports button is registering an internet explorer error for invalid character.

    input type=”submit” name=”LoadButton” value=”Open Report” onclick=”reports.target=’_blank’;” id=”LoadButton” style=”font-family:Arial;font-size:Small;font-weight:bold;”

  27. Chris

    It could be issues with ‘_blank’ wordpress seems to change it to an unusual type of apostrophe. I would recommend retyping the lines out by hand in visual studio that you changed on the button tag and that might fix the issue. I had considered that as a possibility

  28. Dan,

    What I would recommend doing is exposing a public get property your master page for WhatEverYourFormNameIs.ID, then in your child pages on the PageLoad event add inside your if(!Page.IsPostBack) wrapper statement

    btnSomeSubmitButton.OnClientClick = string.Format(“{0}.target=’blank’;”, ((YourMasterPageTypeName)this.Master).FormNameID);

    OR you could expose a public method like GetFormTargetNewWindowButtonScript() inside your master page and do something like

    public string GetFormTargetNewWindowButtonScript()
    return string.Concat(WhatEverYourFormNameIs.ID,”.target=’blank’;”);

    and inside your child page on load again

    btnSomeSubmitButton.OnClientClick = ((YourMasterPageTypeName)this.Master).GetFormTargetNewWindowButtonScript();

    This was all coded freehand in my response window so it’s possible I have a syntax error in one of these lines but it should be clear what my intent was. Let me know if either of these solutions works out for you!

  29. Hi ,
    I also have a same problem but let me tell you where i got problem.
    1) i have a master page file (masterpage.master) and there is a …elements ..
    2) I hae a content page where I have a button and i use your above script as below but i did not find a form (.Form1.ID) from property list after closing second last parantesis.

    button1.OnClientClick = string.Format(”{0}.target=’blank’;”, ((masterpage.master)this.Master).

    I did not find the form and neither their ID. I think that should be like below but did not find.

    button1.OnClientClick = string.Format(”{0}.target=’blank’;”, ((masterpage.master)this.Master).Form1.ID

  30. Thanks a lot.

    I solved my problem with this line in the page load

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

    It was a great Idea by you. Thanks again:)


  31. Hi Chris,
    can you please suggest me how can i access ftp return code using C#.
    Based on the return code i need to call a procedure.


  32. Dan,

    Thanks for posting your solution, you got the exact idea I was going for. It also points out one of my biggest annoyances with ASP.NET web forms is the layers of obfuscation that are forced upon the IDs of elements. That’s one of things I think is great about ASP.NET MVC is the much stronger level of control you have over your true html output.


    Take a look at Dan’s comment.

  33. Hello, first of all sorry about my english.

    It works fine form me, but i have got a problem:
    I click my button and a window opens in a blank page. All correct.
    I close this window, i try to click another button, and another button try to do the same as the button which has got target blank. And the new button has its own code. It execute its code and then do the postbackurl, but this other button has not got this property!!

    Thank you!

  34. Mahoni,

    I’m not sure I understand your question, is the problem that the 2nd button causes a new window to display when you want the 2nd button to stay in the original window?

    If this the case read the bottom of my post as I updated for it, otherwise please clarify and I’ll try to help.

  35. Chris, Thank you so much. I have been doing it all wierd ways by creating an iframe and opening the new window in it. Glad I saw your post. Better late than never 🙂 Thanks once again.

  36. Chris,
    This is great, and helped me alot. I wanted to add one thing…

    If you are using this logic inside of an ASP.NET UpdatePanel, you need to add a postback trigger for the control that contains this code.


    • Jesse,

      I’m always glad to hear that my blog helped you, and yes you’d be right since the button does need to do a full post back for this to work so it fully makes sense that you need to add the trigger settings for it if you’re using any type of AJAX.


  37. protected void btnNewEntry_Click(object sender, EventArgs e)

  38. I had been trying to open a report in a new browser window after the report information had been validated, sorted (yada yada),and then redirect the origional page back to the Reports generating page.

    I dont know if my code will help anyone else…. But here…

    Response.Write(“window.open(‘../Reports/Sales.aspx’,’_blank’);”); // The Popup URL
    Response.Write(“window.open(‘../SiteAdmin/Reports.aspx’,’_self’);”); // The Redirect URL

    Some people prob have really fancy ways of doing it, but this way works for me!

    Happy Coding!


  39. Ok Hurray… Lets try that again shall we…

    Response.Write(“”); // Should say Response.Write(“script”); with
    Response.Write(“”); // Should say Response.Write(“/script”); with

    Sorry bout that ppl…

    • Thanks for your comment Rob, that is definitely a viable way to do this also but my goal was to avoid as much as possible needing to either code or inject javascript into the page but it’s always good to see another way that no one else has pointed out yet since it might help someone later.

  40. Hello,

    I tried the as

    Button is inside the gridview and grid under the UpdatePanel.
    It does not open the new window, Can anybody tell me what I am missing or I can’t do it.

  41. Hi all,
    I had the problem of opening a popup on a Response.Redirect instruction from a page which used an AJAX-enabled masterpage (with a ScriptManager and an UpdatePanel). I tried the above solutions but they didn’t work, apart from the javascript one. I solved my problem using javascript on just one line of code in the button-click handler method. Here it is:

    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "uniqueKey" + DateTime.Now, "window.open('MyUrl.aspx','_blank');", true);


  42. oops, here is a challenge…

    i want it to SELECTIVELY open in a new window, don’t think this solution will work for that.

    I have a simple input box which is a search, on submit i search based on user input, if there is a match i want to redirect to a page in a new window, if there is not a match i want to stay on that page and show a panel.

    any ideas?


    • Chad,

      If the case is you selectively want to do it, you’ll find it much easier to use Page.ClientScript.RegisterClientScript and just inject in a javascript:window.open event.

  43. Hi Chris,

    Thanks for the posting. I have been trying for this since so many days. I had many image buttons on our website’s home page. When I use the target=’_self” it fixed the issue I was having.

  44. I always use this code !

    String clientScriptName = “ButtonClickScript”;
    Type clientScriptType = this.GetType ();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager clientScript = Page.ClientScript;

    // Check to see if the client script is already registered.
    if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
    StringBuilder sb = new StringBuilder ();
    sb.Append (“”);
    sb.Append (“window.open(‘ ” + url + “‘)”); //URL = where you want to redirect.
    sb.Append (“”);
    clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());

  45. Hi,

    With an asp linkbutton once the first click has been made the onclientclick command overwrites the onclick command, and thus i lose the link to run my command which is the whole point of using a linkbutton and not hyperlink. So this only works for first click and then is becomes a dead button.

  46. OnClientClick=”aspnetForm.target =’_blank'”

    showing error
    Microsoft JScript runtime error: ‘aspnetForm’ is undefined

  47. Hi,

    I am in the sutuation where the open in a new page should be conditional, but should only be done when the button is clicked.
    Do you maybe have a clean solution?


  48. hello chris from france

    i use vb.net 2008

    i have several identical pages with datalist

    inside datalist i have declared a buttonimage in wich i declare a commandargument that is the link to a new page and a imageurl that is the url of the image



    in the code i have the following source

    Protected Sub DataPro_FicheClick(ByVal sender As Object, ByVal e As EventArgs)

    Dim ImgBtn As ImageButton = sender
    Dim Lnk As String = ImgBtn.CommandArgument


    End Sub

    it works for 4 pages but not for one

    when i look at the source code of the page i have the form id correct

    but i do not see the datalist as for the others

    on the web page the datalist exists

    when i click on the imagebutton it does not execute the target=’_blank’

    the difference with the other pages is that page is biggest

    on all the pages the events for the datalist are the same (selectedindex, itemdatabound) and the itemdatabounded event is in a commun module unedr app_code

    is it a bug of vb 2008 ?

    is there something to do in the web.config ?

    i hope that you can help me and maany thanks in advance

  49. Hi Chris thanks for posting this. However, after I tried it, the new page opens but in the same window. What could have happened? I have read all the comments but none seemed to have experienced the same. Can you help? thanks again

  50. Why do I get the error?:

    Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.

  51. It’s not worked if I use with update panel. How can I make it work?

    I tried with the suggested code above
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), “uniqueKey” + DateTime.Now, “window.open(‘MyUrl.aspx’,’_blank’);”, true);

    It’s still not worked.

    Thank you very much.

  52. following code not working
    can any budy help to open a new window when I click on link button in grid view

    protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
    if (e.CommandName == “cmd”)
    string url = Server.MapPath(“~//Html\\abc.htm”);
    LinkButton lbtn = (LinkButton)GridView1.Rows[RowIndex].Cells[1].FindControl(“hypeno”);
    lbtn.Attributes.Add(“onClick”, “window.open(‘url’, ‘height=400,width=600’) return false”);

  53. Try this code work for me !
    I hope this will work for u
    best luck!

    string file =”abc.html”;
    string url = “Http:\\Html/\\” + file;
    string strScript = “window.open(‘” + url + “‘,’_blank’)”;
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), “strScript”, strScript, true);

  54. Hi Chris.
    I tried OnClientClick=”aspnetForm.target =’_blank’;” but it didnt work for me.
    where is the problem might be??

Leave a Reply to dotnetchris Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s