Tuesday, October 18, 2011

Navigate to Previous Page in ASP.NET

 
Using Request.UrlReferrer, we can get the Previous page URL of the current
 request.Previous Page information is available in the Request.UrlReferrer
 property only if user is redirected to the current page from some other
 page and is available in the !Page.IsPostBack of Page Load event of the form.
 Here we use ViewState because it can be used if you want to store the values 
on postback to the same form. 
ViewState is used for retaining values between multiple requests for the same
 page
This is the default method that the page uses to preserve page and control property 
values between round trips.  
 
... Default Page... 
<asp:Button runat="server" ID="btnBack" Text="Back" onclick="btnBack_Click" />
 
 
----------------------.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) 
//check if the webpage is loaded for the first time. 
{
            ViewState["PreviousPage"] = 
  Request.UrlReferrer;//Saves the Previous page url in ViewState 
}
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        if (ViewState["PreviousPage"] != null) //Check if the ViewState  
//contains Previous page URL        {
            Response.Redirect(ViewState["PreviousPage"].ToString());
//Redirect to
   //Previous page by retrieving the PreviousPage Url from ViewState. 
}
    } 

No comments:

Post a Comment