devxlogo

Redirecting to the real referrer page during a postback

Redirecting to the real referrer page during a postback

Say that you have a page loaded from another page, and that in this page you have a “Save and Return” button that does something and returns to the previous page. For example you may have an Orders page that loads a Details page, where you make some changes and press the button to save the changes and return to the Orders page. You may think that the following code would work just fine:

Response.Redirect(Request.UrlReferrer.ToString())

But this isn’t the case. In fact, when a web form submits itself and generates a postback, the referrer page becomes the page itself! The solution is very simple though. When the page is first loaded (i.e. it is not a postback), you save the real referrer page in the page’s ViewState:

Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)    If Not Page.IsPostBack Then        ' Save the referrer Url        ViewState("ReferrerUrl") = Request.UrlReferrer.ToString()    End IfEnd Sub

Then, when the “Save and Return” is clicked you retrieve the Url saved in the ViewState, and redirect to it:

Protected Sub SaveAndReturn_Click(ByVal sender As Object, ByVal e As EventArgs)    ' do something here, e.g. add/update some DB records        ' redirect to the previous page    Response.Redirect(ViewState("ReferrerUrl").ToString())End Sub

This tip is taken from Marco Bellinaso’s and Kevin Hoffman’s “ASP.NET Website Programming – VB.NET edition” (Wrox Press). You can read two entire sample chapters of the C# edition from our Book Bank: Chapter 4: Mantaining the site and Chapter 11: Deploying the Site.

See also  Does It Make Sense to Splurge on a Laptop?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist