Reputation: 2527
I have some regular input webpage where users type in some details about item. Then after the user presses the submit button she is redirected to a webpage saying that everything went fine. The problem is that if she clicks the back button then the input page is displayed again, and if she hits the sumbit, the form is re-submitted and another item is being written to the database, which is not desirable, of course.
I'm using ASP.NET MVC in C#. What is the best-practice way to deal with this situation?
Upvotes: 3
Views: 3174
Reputation: 13692
You can use TempDate and a hidden form value to both store a unique token, and compare them on the postback.
Like this:
public ActionResult FormDemo()
{
var guid = Guid.NewGuid().ToString();
ViewData.Model = guid;
TempData.Add("guid", guid);
return View();
}
[HttpPost]
public ActionResult FormDemo(string name, string guid)
{
if(guid != (string)TempData["guid"]) return new HttpStatusCodeResult(500);
return RedirectToAction("FormDemoReceipt");
}
public ActionResult FormDemoReceipt()
{
return Content("Form submitted OK!");
}
My FormDemo view looks like this:
@using (Html.BeginForm())
{
@Html.Hidden("guid", Model)
@Html.TextBox("name");
<input type="submit"/>
}
Upvotes: 0
Reputation: 14798
You can create a hidden form element that marks the form as unique. Each time the form is written by the server, create a new random unique value. When the form is submitted, have the server check that the identifier has not been used before.
The problem is if you want to allow the user to press back and re-submit to create a second entry, there is no way to tell if the user intended to make a second copy or not. What you could do in this situation is make a link which takes the user to the same form, but with a newly generated hidden form element containing the unique identifier.
Upvotes: 2