Search code examples
javascriptasp.netresponse.redirect

How to remove target='_blank' after postback event?


I have added a button on my asp page and I am executing some process at server side then redirecting a link to another page.

What I am doing in my page is that I am calling a method On asp:Button OnClientClick event where I am assigning a aspnetForm.target='_blank' to navigate the page in different tab.

ASP.NET CODE:

<asp:Button ID='btn' runtat='server' OnClientClick='ShowPage();' Text='Show Page' />

JavaScript CODE:

function ShowPage() {
    aspnetForm.target = '_blank';
}

I am using using Response.Redirect() method to navigate a page. This method is called only after verifying required validations at server side.

C#.NET Code

If (ValidData())
{
   Response.Redirect('myPage.aspx?preview=true', True);
}

The validation code is huge and there are also some further process are being executed during the validation. So, I cannot use WebMethod for ajax call.

Everything is working correctly but, the problem is that there are some other links and buttons also. So, when i click on any of them the page is also redirecting for that particular request and I don't want to do that. It happens because the `aspnetForm.target='_blank`` is still exist in the asp form and it will perform same action for other links also.

My requirement is that the page should be navigated in new tab only when a particular button is pressed. other navigation process should be done is same page. I am wondering that is there any method that i can use to remove target = '_blank' after postback.

I cannot use rel='external' because I am not using anchor<a> tag. I am using asp:Button which is also handling some server side events.

Or is there any other way that i can use to navigate the page in new tab without using target='_blank' method?

EDITED:

Currently I am using Page.ClientScript.RegisterStartupScript() to execute my Popup window script. But, when the popup blocker is on it doesn't work. So, I have to chose another way.

Page.ClientScript.RegisterStartupScript(Me.GetType(), "OpenWindow", "window.open('myPage.aspx?preview=true','_newtab');", True)

Solution

  • I have solve my issue by using setTimeout() method. I am resetting form attribute target to _self after 1000 milliseconds.

    Javascript Code:

    function ShowPage() {
        aspnetForm.target = "_blank";
        setTimeout(function() {
            aspnetForm.target = "_self";
        }, 1000);
    }
    

    ASP.NET Code

    <asp:Button ID='btn' runtat='server' OnClientClick='ShowPage();' Text='Show Page' />
    

    And, I can use my existing method Response.Redirect() which will not trigger the Popup Blocker message.

    It will reset the target attribute of form to _self after navigating new tab.