Old fart Old fart - 2 years ago 137
Javascript Question

Prevent Double Submit / Post on ASP.NET MVC page

I am hoping for some feedback about the method I intend to use for preventing duplicate records in an ASP.NET MVC 4 application, and the knock on effects I have not though of for the users experience.

The web form has six input fields and a save button (as well as a cancel button), Users can take up to 10 minutes filling in the form.

Once the fields are submitted via a post the page is redirected on success / failure to a different page, after the data is recorded in a database table using a new Guid as the primary key.

To stop the users pressing the save button many times, but allowing the browser to repost the request on a closed connection I intend to provide the Guid for the new records primary key as a hidden input field when the form is rendered.

If the repost happens, or the user presses save multiple times, the database server will reject the second post of the record because of a duplicate key, which I can check for and cope with server side.

But does this create bigger problems for me?

Answer Source

You can prevent the double click from the client side using some jQuery, if you'd like.

In your HTML, have your submit button be something like this:

<a id="submit-button"> Submit Form </a> <span id="working-message"></span>

In JavaScript (jQuery):

   $('#working-message').html('Working on that...');
$.post('/someurl', formData, function(data){
//redirect to all done page
   $('#working-message').html('Submit failed, try again?');
}); // end on click

This will hide the button before it even tries to submit, so the user can't click twice. This also shows progress, and on failure, allows them to resubmit. You may want to think about adding a timeout to my above code.

Another alternative is to use jquery to grab the form $('#form-id').submit(), but you wouldn't be able to track the progress as easily like the ajax call I've done.

EDIT: I would still recommend looking at ways to prevent double submission from a server-side stand point, just for security reasons.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download