I follow the PRG pattern to avoid form resubmission problem when page is refreshed. These are the action metods:
public ViewResult AddDcoument(){
.....
return View();
}
[HttpPost]
public RedirectToRouteResult SaveDocument(Document doc){
//save the document
return RedirectToAction("ViewDocument",new { docId =doc.DocID});
}
public ViewResult ViewDocument(string docID){
Document doc=GetDocumentByID(docID);
return View(doc);
}
When I hit the submit button the document is saved and I get redirected to ViewDocument action and this helps prevent form resubmission when the page is refreshed. But there's another problem, the problem is I can still click the browser back button, which will take me back to the data entry form with all the previously entered data remaining and I can easily click submit again, which means duplicate entry. Now one might say that I need to have something that is unique for an entry that will not let a duplicate to be saved to server. In fact I have it and that is the DocumentID, but it's assigned automatically, not by user input. So how do you handle this case?
UPDATE: I actualy found a way around this issue. As per this blog and many other SO threads I need to supply the following Http header in order to turn off browser caching:
Cache-Control: no-cache, max-age=0, must-revalidate, no-store
I've tried both the following ways:
The encapsulated, OOP way:
var cache=Response.Cache;
cache.SetExpires(DateTime.UtcNow.AddDays(-1));
cache.SetValidUntilExpires(false);
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoStore();
And by simply appending the header string:
Response.AppendHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
I tried adding them both to the GET method that renders the form and to the POST method that submits the form. But still the form inputs are repopulated from cache.