Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent multiple posts on MVC3?

A user wants to post in his blog, he fills the field and click submit.

The site is running slow, he clicks again, and again, and again.

It was finally saved, but now he check his posts and sees 4 posts.

How can I prevent this from happening? If the user click to submit once I want to do nothing for the next clicks or abort previous and start a new post, whichever makes more sense or is recommended.

In a form with

@using (Ajax.BeginForm(...))
{
}
like image 864
BrunoLM Avatar asked May 03 '11 12:05

BrunoLM


2 Answers

The easiest way to achieve this is to disable submit buttons after click.

Add the following javascript (jQuery) to your view:

$(function () {
    $('input[type="submit"]').click(function() {
        $(this).attr('disabled', 'disabled');
    });
});

Remember to enable buttons after ajax request complete if neccessary:

$('input[type="submit"]').removeAttr('disabled');

UPDATE:

It's better to disable the submit button in forms submit event handler, because an user can submit the form by pressing enter button:

$(function () {
    $('form').submit(function() {
        $('input[type="submit"]', this).attr('disabled', 'disabled');
    });
});
like image 156
bniwredyc Avatar answered Oct 05 '22 13:10

bniwredyc


There are many solutions.

One is to create a random GUID with the form as a hidden field which is inserted into database with the post. Before inserting, it checks if GUID already exists.

Alternatively you can use a real property such as DateTime (which is sent to the client side as a hidden field) or "Post title".

like image 34
Aliostad Avatar answered Oct 05 '22 11:10

Aliostad