I'm having trouble with a simple ASP.NET application and the back button after a post back.
The page in question has a simple form on it, some text fields etc, and a dropdown that does a postback (autopostback).
The "normal" flow is the user fills out the form and perhaps changes the dropdown. Based on the dropdown value the page content might change.
The problem I'm having is that after the user has changed the dropdown and the postback has completed then the user clicks the back button. They see a "webpage has expired" message from IE.
I've set the following:
Response.Cache.SetExpires(DateTime.Now.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.Private);
But that doesn't seem to have nailed the problem.
The actual Cache-Control response header reads as: private, no-cache:"Set-Cookie"
In a classic ASP application the with a Cache-Control response header of just "private" the back button behaves as expected after a "post back".
Is there anyway to force ASP.NET to set the cache-control explicitly to exactly "private"? Or any other solution that results in the back button and postbacks working well together?
Thanks!
Depending on a situation you might get away with this hack/workaround:
private void Page_PreRender(object sender, System.EventArgs e)
{
if (IsPostBack && !IsCallback)
{
Response.Write("<html><head><script>location.replace('" + Request.Path + "');\n" + "</script></head><body></body></html>\n");
Response.End();
}
}
What you're dealing with is actually an old problem. In essence, the reason that you're seeing the "web page has expired" message is that one of the techniques for disabling the "back" button has been employed. The technique sets the cache to a date in the past, therefore causing the browser to show this error if the user clicks the "back" button.
That would be this line of code:
Response.Cache.SetExpires(DateTime.Now.AddMinutes(-1));
This has been an issue, particularly with WebForms ASP.NET because of how the postback works, compared to other frameworks.
For a thorough explanation of all the issues involved, I strongly recommend reading the article linked to below. It does not answer your question directly, but I think you will get more information out of it than a simple answer and will help you think through your options, armed with a better understanding of the issue at hand. Be sure to read parts 1 AND 2.
http://www.4guysfromrolla.com/webtech/111500-1.shtml
I do have an idea on how to make the "back" button behave like a "back" button again, so that postbacks aren't treated as a page navigation:
Personally, I've adopted a (arguably hackish/sloppy) approach of just putting things in an UpdatePanel when I don't want the postbacl/back button conflict, since I use Ajax in most of my apps anyway. This forces the "back" button to actually go back to the previous page, rather than staing on the same page, but reverting to the control values as they were before the postback.