MVC中重复提交表单

MVC中重复提交表单

本文介绍了通过单击两次提交,避免在Asp.net MVC中重复提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用提交按钮在Asp.net MVC中呈现一个表单.成功将记录添加到数据库后,页面将重定向.以下是代码:-

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.

推荐答案

我不认为这与注释中引用的答案完全相同,因为该链接适用于spring MVC,而此问题适用于.NET. MVC.

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.

我前一段时间实际上花了几个小时,并提出了以下建议.此javascript可以与不引人注目的jquery验证很好地挂钩,您可以将其应用于具有<input type="submit"的任何形式.请注意,它使用的是jQuery 1.7的on函数:

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('input[type="submit"]');
    setTimeout(function () {
        button.removeAttr('disabled');
    }, 1);
});
$(document).on('submit', 'form', function () {
    var button = $(this).find('input[type="submit"]');
    setTimeout(function () {
        button.attr('disabled', 'disabled');
    }, 0);
});

需要setTimeouts.否则,即使客户端验证失败,您最终也可能获得一个在单击后被禁用的按钮.我们将其保存在全局javascript文件中,以便将其自动应用于我们的所有表单.

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.

这篇关于通过单击两次提交,避免在Asp.net MVC中重复提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:17