I am rendering a form in Asp.net MVC with a submit button. The page redirects after successful record addition into the database. Following is the code :-
[HttpPost] public ActionResult Create(BrandPicView brandPic) { if (ModelState.IsValid) { if (!String.IsNullOrEmpty(brandPic.Picture.PictureUrl)) { Picture picture = new Picture(); picture.PictureUrl = brandPic.Picture.PictureUrl; db.Pictures.Add(picture); brandPic.Brand.PictureId = picture.Id; } db.Brands.Add(brandPic.Brand); db.SaveChanges(); return RedirectToAction("Index"); } return View(); }
But, while testing, I saw that if the form is clicked again and again, the multiple entries are submitted and saved into the database.
How can i make sure that if the form has been submitted once to the server, then no duplicates are submitted.
Returning "false" from the submit handler will prevent the form from submitting.
Original answer for ASP.NET MVC (.NET Framework 4.x) First, make sure you're using the AntiForgeryToken on your form. [HttpPost] [ValidateAntiForgeryToken] [PreventDuplicateRequest] public ActionResult CreatePost(InputModel input) { ... }
Add("onclick", " this. disabled = true; " + ClientScript.
I have the following code for avoiding the double clic: jQuery. fn. preventDoubleSubmit = function () { var alreadySubmitted = false; return jQuery(this).
I don't think this is quite a duplicate of the answer referenced in the comment, since the link is for spring MVC, and this question is for .NET MVC.
I actually spent a few hours on this a while back, and came up with the following. This javascript hooks nicely with the unobtrusive jquery validation, and you can apply it to any form that has <input type="submit"
. Note that it uses jquery 1.7's on
function:
$(document).on('invalid-form.validate', 'form', function () { var button = $(this).find(':submit'); setTimeout(function () { button.removeAttr('disabled'); }, 1); }); $(document).on('submit', 'form', function () { var button = $(this).find(':submit'); setTimeout(function () { button.attr('disabled', 'disabled'); }, 0); });
The setTimeouts are needed. Otherwise, you could end up with a button that is disabled after clicked even when client-side validation fails. We have this in a global javascript file so that it is automatically applied to all of our forms.
Update 16 Nov 2020 by @seagull :
Replaced selector input[type="submit"]
with :submit
so it will work with <button type="submit" />
as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With