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 a 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);
}
}
}