How do I prevent multiple form submission in .NET MVC without using Javascript?

后端 未结 13 2079
情深已故
情深已故 2020-11-28 02:36

I want to prevent users submitting forms multiple times in .NET MVC. I\'ve tried several methods using Javascript but have had difficulties getting it to work in all browser

相关标签:
13条回答
  • 2020-11-28 03:07

    This works on every browser

     document.onkeydown = function () {
            switch (event.keyCode) {
                case 116: //F5 button
                    event.returnValue = false;
                    event.keyCode = 0;
                    return false;
                case 82: //R button
                    if (event.ctrlKey) {
                        event.returnValue = false;
                        event.keyCode = 0;
                        return false;
                    }
            }
        }
    
    0 讨论(0)
  • 2020-11-28 03:09

    Use the Post/Redirect/Get design pattern.

    PS: It looks to me that the answer by Jim Yarbro could have a fundamental flaw in that the __RequestVerificationToken is stored in the HttpContext.Current.Session["LastProcessedToken"], this value will be replaced when a second form is submitted (from say another browser window), at this point it is possible to re-submit the first form and it won’t be recognized as a duplicate submission? For the proposed model to work wouldn’t a history of __RequestVerificationToken be required(?), this wouldn’t be feasible.

    0 讨论(0)
  • 2020-11-28 03:10

    what if we use $(this).valid()

     $('form').submit(function () {
                if ($(this).valid()) {
                    $(this).find(':submit').attr('disabled', 'disabled');
                }
            });
    
    0 讨论(0)
  • 2020-11-28 03:14

    I've tried several methods using Javascript but have had difficulties getting it to work in all browsers

    Have you tried using jquery?

    $('#myform').submit(function() {
        $(this).find(':submit').attr('disabled', 'disabled');
    });
    

    This should take care of the browser differences.

    0 讨论(0)
  • 2020-11-28 03:15

    Dont reinvent the wheel :)

    Use the Post/Redirect/Get design pattern.

    Here you can find a question and an answer giving some suggestions on how to implement it in ASP.NET MVC.

    0 讨论(0)
  • 2020-11-28 03:15

    You can also pass some sort of token in a hidden field and validate this in the controller.

    Or you work with redirects after submitting values. But this get's difficult if you take heavily advantage of ajax.

    0 讨论(0)
提交回复
热议问题