How to go back to the previous page in ASP.NET 2.0

Posted by: Suprotim Agarwal , on 12/2/2007, in Category ASP.NET
Views: 315152
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 (only for understanding, not to be used in production apps)
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 (which you should avoid in all cases), 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 (avoid static variables though). If you have experimented with any method, you can share it over here with other readers.
I hope this article was useful and I thank you for viewing it. Happy Coding!! 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


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 2, 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 4, 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 7, 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 5, 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 2, 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 2, 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 1, 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 1, 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 2, 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 4, 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 2, 2010 8:12 PM
Thank you it works. Great Job!!!
Comment posted by Sachin Hayatnagarkar on Monday, September 6, 2010 2:45 AM
Thank you for sharing the ways... !!! It works fine... !! Happy coding
Comment posted by gwensink on Wednesday, October 13, 2010 10:58 AM
I did something that is even simpler and much cleaner. I took the call to the referrer and dynamically added it to a hyperlink control. Done!
Comment posted by Rakesh on Thursday, November 11, 2010 4:15 PM
Request.UrlReferrer  not working with IE. it is ok for firefox and chrome
Comment posted by sravani on Thursday, January 27, 2011 12:33 AM
Thank's

I have tried the page navigation technic which you have explained in the metho1 using static variable and urlreferrer, when I try to run the application Iam getting an error like "object reference not sent to an instance of an object".can you please give me a solution for this error please.  
Comment posted by sravani on Thursday, January 27, 2011 1:05 AM
Sorry for the comment which I have posted before is Iam getting error when Iam using method1.
Now again I have tried the same Iam getting.
Method1 is working.

Thank you and once again sorry.
Comment posted by Jonathan on Wednesday, March 2, 2011 10:16 AM
Good stuff. Here are a couple of examples that do not require anything in the code-behind:

<a href="<%: Request.UrlReferrer.ToString() %>">Back</a>

<input type="button" onclick="parent.location='<%: Request.UrlReferrer.ToString() %>'" value="Back" />

Be sure to use <%= Request.UrlReferrer.ToString() %> if you are targeting pre-.NET 4 framework. Notice the '=' instead of ':' (see this article http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx)
Comment posted by Monika Verma on Saturday, March 12, 2011 7:29 AM
Very good article. Really Good ...helpful.Thanks.
Comment posted by Ankit Vijay on Saturday, April 16, 2011 4:49 PM
Method 1 is logically incorrect. You cannot use static variable to store a user specific data. Static variable for a specific aspx page is shared across the application for all the users. Initializing, the variable as String.Empty also will not help.For example: Let us consider we have pages A, B, and C. Page A is our main page where redirect logic is written.
Suppose User X was comes to Page A from page B. At the same time before user X clicks on button on Page A, user Y comes to Page A from Page C. At the page load the static variable prevPage will be initialized to Page C. Now when user X clicks on the button, instead of being redirected to Pace B, he will be redirected to page C.
Comment posted by Uma Lavanya on Thursday, August 4, 2011 7:45 AM
Method 2 is not working in ie browser
Comment posted by Uma Lavanya on Thursday, August 4, 2011 7:47 AM
Method 2 is not working in ie browser
Comment posted by priykanat MistRy on Sunday, November 13, 2011 6:36 AM
thxxx u
vry much....
:)
Comment posted by Gus on Tuesday, November 29, 2011 7:59 AM
Helped me out!

many thanks for posting this!
Comment posted by javed on Tuesday, January 31, 2012 7:03 AM
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 tony on Monday, April 2, 2012 4:27 PM
me ayudo mucho eres la leche,.. padre!!
Comment posted by Sravanam Prasad on Friday, June 1, 2012 7:09 AM
The code is good but its need some modification
Comment posted by minakshi on Thursday, June 21, 2012 1:57 AM
The code is good but its need some modification
Comment posted by Iwan on Tuesday, July 31, 2012 9:11 AM
I just wanted to say that this was a great article. Very precise.
Comment posted by Laura Arevalo on Wednesday, August 15, 2012 9:42 AM
muchas gracias me sirvió mucho
Comment posted by Sriram on Friday, August 24, 2012 7:43 AM
Its Saved my time, Thanks a lot, Sir.
Comment posted by Zameer on Wednesday, December 19, 2012 2:47 AM
Thanks alot A+1 it helped alot..
Comment posted by Mike Clifford on Wednesday, January 23, 2013 12:15 AM
Thanks Heaps. Used your method 3 using vb.net, worked great.
Comment posted by Mr Mahammad Lutfur Rahman on Tuesday, February 12, 2013 9:01 AM
RRF;MLR/BBA/82
Comment posted by jayesh on Thursday, March 14, 2013 5:20 AM
no commentes
Comment posted by Dhaval Rane on Tuesday, June 4, 2013 1:37 AM
very helpful artical
Thank you.
Comment posted by Dhaval Rane on Tuesday, June 4, 2013 1:37 AM
very helpful artical
Thank you.
Comment posted by LĂȘ Quang on Tuesday, September 3, 2013 11:03 PM
Thanks
Comment posted by Rajesh on Thursday, October 31, 2013 7:25 AM
Thanks alot. you saved my time
Comment posted by rainu on Saturday, February 22, 2014 12:34 AM
it helped for my project thanks a lot......+1 :->

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