Friday, December 21, 2012

Navigate to Previous page in history

Imagine you have two pages, first.aspx and second.aspx. using the below code you'll be able to navigate to first page history ignoring the posts backs occurred in second page.

Browser back button supports navigating to a previous page with the previous states of the page controls. Imagine that you want to navigate back to a page you used before some tasks that caused posts backs and a page navigation. Now you need to click the back buttons several times to go back to that page.

You can use below method in that case.

Add the below code in page header tags.

function Backward(oSpyID) {
// The hidden post-back spy or counter field
var spy = null;
// Total number of post-backs
var refreshes = new Number(0);
// Allows the actual previous page to be selected
var offset = new Number(1);
spy = document.getElementById(oSpyID);
refreshes = new Number(spy.value) + offset;
// Redirects to the actual previous page

Now add the back button in the HTML page.

<a href="javascript:;" title="Back">
<asp:ImageButton runat="server" ID="hpBackward" Enabled="true"
ImageUrl="~/Images/back_button.png" Height="29px" /><span>Back</span><span
<input type="hidden" id="inputPostBackSpy" runat="server" />

Below code in the .CS page

protected void Page_Load(object sender, EventArgs e)
   if (!Page.IsPostBack)
    hpBackward.Attributes.Add("onclick", "Backward('" + inputPostBackSpy.ClientID + "')");
    PostBackSpy = 0;
    PostBackSpy = PostBackSpy + 1;

private int PostBackSpy
  get { return Convert.ToInt32(inputPostBackSpy.Value); }
  set { inputPostBackSpy.Value = value.ToString(); }

No comments:
Write comments
Recommended Posts × +