Going back to previous page

Benjamin Chew 42 Reputation points
2021-10-28T06:45:50.817+00:00

I have a back button on most of my pages. when user click on the Back button, I want them to be redirected previous page in their history.

i am having the following issue

Request.Referrer won't work with the following example user browser from page1.aspx -> page2.aspx -> page3.aspx

when user navigate from page2.aspx to page3.aspx, getting Request.Referrer would be page2.aspx which is correct, when user click back on page3.aspx, I used Response.Redirect to the referrer URL, which is page2.aspx. but now on page2.aspx, the referrer would be page3.aspx. so if pressing back here would cause the page to be redirect to page3.aspx which is wrong.

what I wanted is the following

  1. the back button to works similar to the browser back
  2. history.back is empty to redirect to homepage
  3. if the URL in history.back does not belong to my site, user to be redirected to homepage also.
Developer technologies | ASP.NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,096 Reputation points
    2021-10-29T06:37:20.383+00:00

    Hi @Anonymous ,
    According to your description,I think,you could session your UrlReferrer. And you only need to check if the session is null.
    Page2:

    protected void Page1Button_Click(object sender, EventArgs e)  
    {  
     Session["url"] = Request.UrlReferrer.AbsoluteUri.ToString();  
     Response.Redirect("page3.aspx");  
     }  
    

    Page3:

    protected void btnBack_Click(object sender, EventArgs e)  
    {  
        if (Session["url"].ToString() != null)  
        {  
             Response.Redirect(Session["url"].ToString());  
        }  
        else  
        {  
          ......  
        }  
    }  
    

    Best regards,
    Yijing Sun


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.