Retrieving the previous page in history instead of the PostBack page

An article on retrieving the actual previous page instead of the post back page using JavaScript and ASP.NET.

Introduction

We all are quite familiar with the Back and Forward buttons of a web browser. They work exactly as they should, but when dealing with server-side pages that take advantage of post-backs, such as ASP.NET pages, the Back and Forward buttons work a little too well.

For instance, if you were to interact with a drop down list on a page or any type of control that automatically displays results to the same page, then the previous state before the change took place will be added into the browser's memory.

So in this case, what happens when you click the Back button?

That's right, you get the previous state of that page and not the actual page that you browsed from or were sent from.

The Solution

Oh, it's simple. Just write your own backward and forward JavaScript functions and track the number of times the page commits an action or post-back. There are three easy steps to accomplish this. Before we get started, note that templating is popular with server-side pages (especially with ASP.NET). Templating can cause the actual ID of a web-control to change after the page is rendered, so we will take advantage of the ClientID property found in all ASP.NET web-controls since it knows what the rendered ID will be.

Step 1

Insert the following JavaScript functions in a referenced (.js) file or within script tags:

Comments and Discussions

I am working on a page in .net 1.1, where post data is used at the beginning to retrieve the ID from the database using a dropdownlist. One of the .net server controls on the page is to link to another page using asp:linkbutton and the other control is to link back to the original page using asp:hyperlink with javascript: history.go(-1). The message, "The page cannot be refreshed without resending the information, Click Retry to send the information again, or click Cancel to return to the page that you were trying to view." is received when I clicked on the hyperlink back to the previous page.

There is another page on the same site. It has almost the same functionalities. It has no problem to go back to the previous page. I checked all possible causes in both html page and code behind. I couldn't find any difference between these two pages.