I have a small class that displays an alert via Javascript. I am using this class on a page that checks if the user entered valid zip code. If a valid zip code is not entered, an alert is displayed, and the page is posted back to the same page so they can change it. If they enter a valid zip code, they are redirected to another page. The problem is that if they hit the back button on their browser, the alert is displayed regardless of whether the zip code is valid or not.
Here is the flow:
Zip entry page -> Enter Zip -> Check Zip
if valid zip -> goto overview.aspx if not valid zip, goto zip entry page
On overview.aspx, if they hit their browser’s back button, the alert is displayed. I don’t want this to happen. Below is the code I have for the alert class which works great. And below that the code that checks and displays the alert when the LinkButton is clicked.
protected void GotoReview(object sender, EventArgs e) { if (ValidateZipCode(ZipCode)) { Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}", ProductCode, ZipCode)); } else { Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code."); } } private bool ValidateZipCode(string zip) { if (zip.Length < 5 || zip.Length > 5) { return false; } if (!Regex.IsMatch(zip, @"^(\d{5}-\d{4})|(\d{5})$")) { return false; } return true; } public static class Alert { public static void Show(string message) { string cleanMessage = message.Replace("'", "\\'"); string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>"; Page page = HttpContext.Current.CurrentHandler as Page; if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) { page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); } } }
Back buttons work differently on all browsers, some browsers will retrieve the newest version, others will simply return what the latest on disk copy is.
The best thing to do here is probably to bust out the old javascript and add an OnSubmit to the form to check for proper validations, jquery would be a great tool in this instance.
With this method, no matter the browsers back strategy, your alert will not be called unless they click on the submit button.