Tuesday, February 24, 2009

Navigating to the previous web form or web page

For example: To redirect a user back to search page from the results page if he wants to change the criteria.
history.go(-1) and history.back() don’t usually work because your results page may have submitted or posted back. So most workarounds I have seen involved storing all the values of the previous web-form and then painfully reloading it.
This one is so simple. I thought of it a couple of days back. I’m amazed I didn’t think of it before. It doesn’t even post back on button click!
// Step 1: Count the post backs and store it in a hidden field
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
HidPostBacks.Value = “1”;
}
else
{
int PostBackCount = int.Parse(HidPostBacks.Value);
HidPostBacks.Value = (PostBackCount+1).ToString();
}
}

// Step 2: The html for storing the fields and calling the JS method
<form id=”Form2” method=”post” runat=”server”>
<input type=”hidden” id=”HidPostBacks” runat=”server” value=”0”>
<input type=”button” name=”cmdRefineSearchCriteria” onclick=”goToSearch();” value=”Refine Search Criteria”>
// Step 3: The JS method for going back
function goToSearch()
{
PostBackCount = parseInt(document.forms[0].HidPostBacks.value);
history.go(0-PostBackCount);
}

No comments:

Post a Comment