Question

I have an old application which has numerous webforms. On every aspx page there is a designated back button, which takes the user to the previous page. All the buttons have the javascript onclick event set to history.back().

On one of the aspx pages, the back button would not work at all. We decided to use a server side button that would accomplish the same thing. The onclick event of the button has the necessary code to take the user to previous page.

First I created the onclick event in the following way, but the back button did not work at all. When I went in the debug mode, I found that the prevPage variable was holding the current page URL instead of the previous page URL.

private void btnBack_Click(object sender, System.EventArgs e)
{
    string prevPage = Request.UrlReferrer.ToString();
    Response.Redirect(prevPage);
}

Then I changed the prevPage to a static variable and defined its value to be set inside the if(!IsPostBack) block. Now the back button worked correctly.

static string prevPage = string.Empty;
private void Page_Load(object sender, System.EventArgs e)
{
    if(!IsPostBack)
    {
        prevPage = Request.UrlReferrer.ToString();
    }
}

private void btnBack_Click()
{
    Response.Redirect(prevPage);
}

I did not understand why the first attempt wouldn't work and why second attempt would.

I have a feeling that this might explain if there is something else going on with this particular page that would also not let the history.back() or history.go(-1) work.

Can you please provide some insight into this?

Edit: I am using IE8.

Was it helpful?

Solution

The first attempt would not work because when you click the button the post back has already occurred, therefore the Referrer URL is the one coming from the button (The page you are on).

In my opinion I would not send a request to the server to push the page back a level, it's an unnecessary request when it could be achieved quicker on the client side.

OTHER TIPS

Man, DO NOT use static variable to store previous URL. It will be shared among all sessions and if case when your page can be achieved from different places, users will be confused. If you want to track last page, Session is your best friend.

JavaScript:window.history.go(-2);return false;

That is all you need, put that in a onclientclick or simply in an anchor tag. You need two clicks because the first click will take you to a confirm submission page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top