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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With