开发者

Preventing Multiple Submits in MVC

开发者_如何学编程

In this question disabling the submit button to prevent multiple postbacks was a viable solution to stop (non-malicious) users from posting back multiple times.

This option doesn't work well if you have a view with multiple submit buttons. Take the following example.

//View:

@using (Html.BeginForm("Catalog", "Images", FormMethod.Post, new { onsubmit = "Utility.disable_buttons(this.id);", id = "catalog_form" }))
{
<p>
    <input type="submit" name="btnSubmit" value="Clear" /> |
    <input type="submit" name="btnSubmit" value="Catalog" /> |
    <input type="submit" name="btnSubmit" value="Update" /> |
    @Html.ActionLink("Back to List", "Index")
</p>
}

//Controller:

[HttpPost]
    public ActionResult Catalog(string btnSubmit)
    {
        switch (btnSubmit)
        {
            case "Catalog":
                //More differenter code
                break;
            case "Clear":
                //Different code
                break;
            case "Nothing":
                //Code
                break;
        }
        return View();
    }

In the view, there are three different submit actions. If the buttons are disabled, then their values won't be passed and the controller will not know which button triggered the submit. (The controller always gets null.) Unfortunately, the submitdisabledcontrols attribute does not seem to solve this problem in MVC. Does anybody know how to pass disabled control's values to the server?


Some background info:

  • Disabled form data such as disabled submit buttons will not be posted back to the server: http://www.w3.org/TR/html4/interact/forms.html#h-17.12.1
  • If a form contains multiple submit buttons only the clicked ones value will be posted back to the server: http://www.w3.org/TR/html4/interact/forms.html#successful-controls

If you want to disable all buttons so they are no longer clickable but still want to know what the user clicked the only solution I can think of is a hidden field along with this code:

$(function() {
    $('input[type=submit]').click(function() {
        var form = $(this).closest('form');
        form.find('#hiddenField').val($(this).val());
        form.find('input[type=submit]').prop('disabled', true);
    });
});

If you just want to make sure the user cannot click the other buttons after clicking one you can do this:

$(function() {
    $('input[type=submit]').click(function(event) {
        $(this).closest('form').find('input[type=submit]').not(this).prop('disabled', true);
    });
});

Unfortunately there is no solution (I know of) to bind a handler to the form´s submit and determine which input was clicked. This is not a problem related to your question but makes the above code slightly more complicated.


you can try this

if (coll.AllKeys.Contains("Clear"))
{
  // your code here for this submit
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜