ASP.Net MVC & JQuery: Preventing multiple clicks by disabling submit buttons

Hackered
Tuesday, September 29, 2015
by Sean McAlinden

Without protection it is very easy for an end user to create duplicate records, all it takes it a little latency and a trigger happy user to create twins, triplets and more...

Typically most ASP.Net MVC use jquery validation so the submit buttons should only disable once we know the form is correct and being posted.

To use jQuery validation the following scripts are usually added within your jQuery bundle.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
    "~/Scripts/jquery-{version}.js",
    "~/Scripts/jquery.validate.min.js",
    "~/Scripts/jquery.validate.unobtrusive.min.js"));

The following settings are placed within your web.config appSettings section:

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

The following snippet can be added either directly for the form page or globally in a script file or layout page (useful if you have many forms throughout):

$(document).on('submit', 'form', function () {
    var buttons = $(this).find('[type="submit"]');
    if ($(this).valid()) {
        buttons.each(function (btn) {
            $(buttons[btn]).prop('disabled', true);
        });
    } else {
        buttons.each(function (btn) {
            $(buttons[btn]).prop('disabled', false);
        });
    }
});

How it works?

Firstly it fires when any form is submitted (whether the form was loaded on postback or via ajax).

It then grabs any submit buttons within the form.

If the form is valid it disables the submit buttons, otherwise it (re)enables them.

Summary

If you are using MVC or MVVM frameworks then there are better ways to handle this problem, if however you are just using a little jQuery here and there, this approach can be useful and save you from a few db headaches.