Create new account I forgot my password    

How to go back to the previous page in ASP.NET 2.0
Rating: 56 user(s) have rated this article Average rating: 4.4
Posted by: Suprotim Agarwal, on 12/2/2007, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 83802 times
Abstract: A very common requirement in a project is to build a navigation system between pages. One of the navigation requirements is to go back to the previous page. In this short article, we will explore the various ways to do so.

How to go back to the previous page in ASP.NET 2.0
 
There are various ways using which you can navigate back to the previous page. To keep the example short and simple, I will be using two pages and a few buttons to demonstrate the navigation. So let us get started:
Step 1: Create an ASP.NET Project with two pages, Page1.aspx and Page2.aspx.
Step 2: On Page1.aspx, drag and drop a button control. In the click event, use this code:
C#
protected void Button1_Click(object sender, EventArgs e)
{
     Response.Redirect("Page2.aspx");
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Redirect("Page2.aspx")
End Sub
Step 3: On Page2.aspx, we will be dragging and dropping 3 buttons. Each button will represent a method to go back to the previous page. Let us explore them one at a time:
Method 1 – Using a static variable and UrlReferrer
URLReferrer gets the URL of the previous page that linked to the current URL. To use this property, declare a static variable called ‘prevPage’ in Page2.aspx. Drag and drop a button, button1 on Page2.aspx. On the Page_Load, use the Request.UrlReferrer to populate the prevPage variable with its value. Then on the button1 click event, use this variable to go back to the previous page as demonstrated below :
C#
// static variable
static string prevPage = String.Empty;
 
protected void Page_Load(object sender, EventArgs e)
{
     if( !IsPostBack )
     {
         prevPage = Request.UrlReferrer.ToString();
     }
 
 }
 
 protected void Button1_Click(object sender, EventArgs e)
 {
      Response.Redirect(prevPage);
 }
VB.NET
'static variable
Private Shared prevPage As String = String.Empty
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If (Not IsPostBack) Then
            prevPage = Request.UrlReferrer.ToString()
        End If
End Sub
 
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Redirect(prevPage)
End Sub
 
Method 2 – Using Javascript
Drag and drop another button called button2 on the Page2.aspx. In the Page_Load event, add the following lines of code :
C#
protected void Page_Load(object sender, EventArgs e)
{
Button2.Attributes.Add("onClick", "javascript:history.back(); return false;");
}
 
protected void Button2_Click(object sender, EventArgs e)
{
      
}
 
VB.NET
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Button2.Attributes.Add("onClick", "javascript:history.back(); return false;")
End Sub
 
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
 
End Sub
 
Note : Notice the ‘return false’ snippet used in the Button2.Attributes.Add method. Well this is used to cancel the submit behaviour that occurs on the button click. Since the Click event precedes over the other events, we need to return false to cancel the submit and go back to the previous page.
 
 
Method 3 – Using ViewState
 
If you do not intend to declare a static variable, you can use viewstate to go back to the previous page by using the same UrlReferrer property that we used in Method 1. To do so, drag and drop a third button, Button3 on Page2.aspx. In the Page_Load event, use the ViewState to store the value of the Request.UrlReferrer property. Then access the same value in the click event of the third button to go back to the previous page as shown below:
C#
protected void Page_Load(object sender, EventArgs e)
{
     if( !IsPostBack )
     {
         ViewState["RefUrl"] = Request.UrlReferrer.ToString();
     }
 
 }
 
protected void Button3_Click(object sender, EventArgs e)
{
     object refUrl = ViewState["RefUrl"];
     if (refUrl != null)
         Response.Redirect((string)refUrl);
}
 
VB.NET
 
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If (Not IsPostBack) Then
            ViewState("RefUrl") = Request.UrlReferrer.ToString()
        End If
End Sub
 
 
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
      Dim refUrl As Object = ViewState("RefUrl")
      If Not refUrl Is Nothing Then
          Response.Redirect(CStr(refUrl))
      End If
End Sub
 
 
Well as we saw, it was quiet easy to use these different methods to go back to the previous page. You are free to experiment and use any of these methods. If you have experimented with any method, you could share it over here with the viewers.
I hope this article was useful and I thank you for viewing it. Happy Coding!!
 
 
 
 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by gayatri on Saturday, December 22, 2007 3:53 AM
i have repeater on page 1 as the search results are displayed in it. after going through  page 2 when i go back to previous page the repeater is displayed. pls help me.
Comment posted by sangam on Tuesday, December 25, 2007 6:23 AM
But the variable prevPage is not accepted.
Error: object reference not set to an instance of an object. Please help.
Comment posted by Suprotim Agarwal on Wednesday, December 26, 2007 12:12 AM
Hi gayatri. Where are you creating the repeater control? Page_Load()?
Comment posted by Suprotim Agarwal on Wednesday, December 26, 2007 12:13 AM
Hello sangam, Did you declare the static variable prevPage first as shown in the article?
Comment posted by lspence on Sunday, December 30, 2007 9:45 PM
I have a quick question and an issue I have with the first and last examples. Your first and last examples give me a "Object reference not set to an instance of an object." error. Any ideas on why this might be?

Now your JavaScript example worked fine, except how can I maintain the values that were on previous page? Viewstate is enable for the both pages by the way.
Comment posted by Suprotim Agarwal on Wednesday, January 02, 2008 7:19 AM
lspence, make sure you have declared the static variable static string prevPage = String.Empty; I will try and post a sample later today.
Comment posted by giteshjoshi on Friday, January 11, 2008 5:27 AM
Hi, This article is very interesting and imp. also..... What i found that even if string prevPage is not declared as static, it's working fine. and yes, condition (!IsPostBack) plays an imp. role.

Thanks and Regards,
Gitesh Joshi
Comment posted by coded-henry on Monday, January 14, 2008 5:23 AM
Thanks for this great help. But Please how can one maintain the values on the previous page? This is because, I could have used the PostBackUrl attribute of the button to go anywhere the same way, but I want to preserve the values of the previous page while visiting back. Please help.
Comment posted by sai on Monday, February 25, 2008 12:33 PM
hi..iam trying for this since 3 months.but i didnot get in any site.its very useful article.thanks for ur help.
Comment posted by BEN on Wednesday, July 16, 2008 8:12 PM
Thanks for the source code. Your the great men....
Comment posted by Vishnu on Monday, July 28, 2008 6:00 PM
If I use your code without previouspagetype directive its showing some error... Moreover.. Javascript is not working.. its showing some error i dont know why..

My situation is.. I have a page where I need to redirect to the previous page. I can use two other pages to come to that page.. So i need to detect the previous page and redirect.. Its not working .. Any solution?
Comment posted by Avinash on Friday, August 22, 2008 4:46 AM
Excellent
Comment posted by sunil on Thursday, August 28, 2008 8:00 AM
hi
i m experiment on vb.net code but its not working fine.it goes to previous page but not in recent previous page so if u have any solution for go to recent previous page then sent it to my mail
Comment posted by Shankar on Wednesday, February 04, 2009 10:09 AM
Nice Artiacal
Comment posted by D.lazarov on Saturday, February 21, 2009 7:59 AM
The most complicated problem is the deployment of the site. All other problems can be solved in this way or the other. Up to now i have found few videos (or tutorios as a whole)showing or discussing all the variants of solving this problem,especially the deployment of databases(sql,access).If possible  clarify this matter as much as possible.
Comment posted by rob on Friday, March 20, 2009 7:39 AM
the prevPage should and instance var, not static.  If you call the page from multiple pages, the page will always go back to the last calling page - since the variable is static as you specify.  That might not be the intended behavior!
Comment posted by Reza on Tuesday, March 31, 2009 3:15 PM
very good. tanx
Comment posted by Ramya on Tuesday, April 07, 2009 3:09 AM
Very good article. Good job ...helpful.Thanks
Comment posted by ruhul on Wednesday, April 15, 2009 4:21 AM
how i clear previous page reference in c#
Comment posted by Abhilash on Tuesday, May 05, 2009 5:31 AM
Hi.
Small but, useful tips to remember.
Take care & Thanks.
Comment posted by Does not work on Sunday, May 24, 2009 5:31 PM
The Request.UrlReferrer pointer is throwing a NUll Pointer exception when called on Page_Load, do you know why that might be?
Comment posted by Suprotim Agarwal on Friday, May 29, 2009 1:18 PM
Can you post the code that causes the error?
Comment posted by Siphiwe on Tuesday, June 02, 2009 9:51 AM
Great code, got it to work without any hussles. Great work, just what i was looking for. for everybody else, use the second example you dont loose any values on the url, they are maintained
Comment posted by Sang Pham on Tuesday, June 02, 2009 4:35 PM
Hi, thanks verry much ^^
Comment posted by Abhi on Thursday, June 25, 2009 9:27 AM
Thanks.Its saved my time
Comment posted by francisco on Wednesday, July 01, 2009 7:19 PM
using javascript:history.back() wont trigger Page_Load,

anyone know if the other methods do?,

thanks
Comment posted by francisco on Wednesday, July 01, 2009 7:39 PM
great! using UrlReferrer it triggers page_load.

thank you!

Comment posted by Rahul Rathi on Wednesday, July 29, 2009 3:41 AM
Very Good Article.

Thanks a Lot!!
Comment posted by Alan on Friday, July 31, 2009 7:46 PM
Two issues:
1) If you have multiple simultaneous visitors to your site, they will all be writing to the same static variable. So user A might get redirected back to user B's previous page. In such a case, saving the "static" variable to the visitor session will work. i.e.: Session["Page1.PreviousPage"] = Request.UrlReferrer.ToString();
2) Use of UrlReferrer is dubious. There is no guarantee it will be valid, since it's value must be sent over by the visitor's browser, and users can and do disable this for security concerns. Instead, you may want to keep track of the URLs yourself (i.e. in your global request handler do something like: Session["LastPage"] = Session["CurrentPage"]; Session["CurrentPage"] = Request.Url.ToString(); )
Comment posted by javid on Friday, October 02, 2009 5:13 AM
great articles thank you very much
Comment posted by test on Friday, December 25, 2009 6:31 PM
test
here

you there

i m testing
Comment posted by kranthi on Wednesday, January 13, 2010 6:48 AM
Hi,
Thanks for the great article.I tried to use the methods mentioned in your article.With the methods 1 & 3 I am able to go back to the previous page,but its state is being lost.I tried with the 2nd method as well.It working fine sometimes.But sometimes it needs mutiple clicks instead of one, to go back to the previous page.It may be because we are using jquery tabs in our website.So could you please tell me why am I loosing the state with the methods 1 & 3.
For your information I have also declared static string prevPage = String.Empty;, and I did not change any view state settings for the page.Thanks in advance
Comment posted by Teemu Keiski on Tuesday, January 26, 2010 2:07 AM
Static variables are VERY dangerous in ASP.NET pages...I would avoid in every possible way
Comment posted by Suprotim Agarwal on Wednesday, January 27, 2010 6:05 AM
Teemu: Yes 3 years after writing this article, I too wouldn't use static vars now :)
Comment posted by Neelesh Trivedi on Friday, January 29, 2010 6:34 AM
but Request.Urlrefrer does not works in all cases and with Fire Fox browser it has working issue also by using javascript.history.back() it gives web page expired does this problem of web page expired can be solved by any way
Comment posted by vishal giri on Thursday, February 25, 2010 11:41 PM
good article needs modifications told by alan as those are important to notice please modify those in original article
Comment posted by Rahul Vartak on Friday, June 04, 2010 7:03 AM
Is there any way by which we can pass a value from a source page to destination page when using history.go(<someint>) in Javascript?
Comment posted by Nathalie on Monday, June 21, 2010 6:46 PM
YES!!! Thanks for that! I've been looking all over for this little piece of code! It works, after log in, the user gets redirected to the page they came from. :)
Comment posted by Blessey on Monday, August 02, 2010 8:12 PM
Thank you it works. Great Job!!!

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER