Eric Bergman
Eric Bergman

Reputation: 1443

How to go back to previous page using Javascript in ASP.NET

I have the following scenario:

I have the following script in my page:

function GoBackToPreviousPage () {           
   parent.history.back();
   return false;
}

In Code Behind I have the following

If (some conditions are met)
  Page.ClientScript.RegisterStartupScript(this.GetType(), "GoBackToPreviousPage", "GoBackToPreviousPage();", true);

If the conditions are met I want the page to go back to the previous page, the reason I'm doing this in javascript instead of on the server is because (parent.history.back();) maintains a history of all the previous pages

I noticed that the after the RegisterStartupScript is executed and postback happens the script is executed but it stays on the same page, it does not go back to the previous page

Upvotes: 1

Views: 3731

Answers (1)

Marcus Vinicius
Marcus Vinicius

Reputation: 1908

The problem is caused by the PostBack that occurs before the execution of the javascript function. You click the button and the current page is saved in the browser history. So, when the page reloads and the script executes, you are in the same page. So, a not-so-pretty solution is to go back two pages in history:

function GoBackToPreviousPage() {
    window.history.go(-2);
    return false;
}

Upvotes: 4

Related Questions