Avoid using Javascrpt to Go back to previous page with asp.net WebForms

Hello,

When i tried to quickly implement an easy back button to go to previous page in any web application i worked on i using javascript magical line:

javascript:history.go(-1)

or

window.history.back()

And in most cases this will be enough to handle all cases for example when you worked with ASP.NET MVC, PHP, Python but be carefull from using it with ASP.NET WebForms.

Why?

WebForms heavlly depend on PostBacks and this can introduce issues with our javascript implementation in some cases. For example:

We have a page: Page1.aspx and there is an asp:button, Now when you click on the button and get back on Page1.aspx, in this situation your previous page is still you Page1.aspx

There are another complex secnarios that i faced during my working days using this way for example:

You have Page1.aspx worked as file explorer and loads Sharepoint document library data.
The page contains button1 that invoke javascript alert message and button2 which return you back if you are inside a folder to previous level . Actually all the levels loads in the same page but you want to handle back button. In this situation if you clicked on the button that show alert then goto inside any folder then try to return back you will see the alert message shown which is a strange behaviour.

So the solution with Asp.Net WebForms is to use ViewState and Request.UrlReferrer:

protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
ViewState["RefUrl"] = Request.UrlReferrer.ToString();
}
}
protected void BtnBackToPreviousPage_Click(object sender, EventArgs e)
{
object refUrl = ViewState["RefUrl"];
if (refUrl != null)
Response.Redirect((string)refUrl);
}

That’s all