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(...))
{
}
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');
});
});
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".
How about the minute the user clicks on the action link for the post area you create a real post but set its "Status" to draft?. After you InsertOnSubmit() the post immediately redirect to an action which you retrieve the post and edit it. This happens so fast the user will not notice. So if the site is slow and he clicks on "Submit" multiple times you will not be generating new records just saving to the same record. I using the process on an task list application I working on. See the code below.
Better Task List Ticket Controller
It may not be the fanciest solution but could lead you to a more creative solution that works for you.
My vote is for ActionFilters. This blog post has code to just drop into your project and decorate your actions.