Tuesday, October 2, 2012

Navigate back a page instead of the last PostBack

To go back a page in history instead of the last postback, this concept can be used.
  In the code behind

1.) Preferably, in a base page, create a counter:
private int postBackCount = 0;

2.) Create a HyperLink:
protected HyperLink previousPageLink;

3.) Override ViewState management and store the counter:
protected override void LoadViewState(object savedState)
{
object[] data = (object[])savedState;   
base.LoadViewState(data[0]);   
this.postBackCount = (int)data[1];
}

protected override object SaveViewState()
{
object [] data = new object[2];   
data[0] = base.SaveViewState();   
data[1] = this.postBackCount;   
return data;
}

4.) In either Page_Load or OnPreRender, increment the counter appropriately and set the HyperLink value:
postBackCount = (IsPostBack) ? (postBackCount + 1) : 0;
previousPageLink.Attributes.Add("onclick", string.Format("Backward('{0}')", postBackCount.ToString()));



In the .aspx page
1.) Add the HyperLink
HyperLink
ID="previousPageLink" Runatimg src="/img/back.png" border="0" align="absmiddle">BackHyperLink>

2.) Add the javascript:
script type= text/javascript

function Backward(backCnt)
{
//Total number of post-backs
var refreshes = new Number(0);
//Allows the actual previous page to be selected
var offset = new Number(1);
refreshes = new Number(backCnt) + offset;
//Redirects to the actual previous page
history.go(-refreshes);
}





No comments: