控制器的HttpPost动作被击中两次 [英] HttpPost action of a controller gets hit twice

查看:101
本文介绍了控制器的HttpPost动作被击中两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的申请中的确切情况。

Following is the exact scenario in my application.

我相信这张照片清楚地解释了这个问题。如果您对此有任何疑问,请告诉我。

I believe this picture is explaining the issue clearly. please do let me know if you have any questions in understanding the same.

问题是HttpPost操作被调用两次导致两个条目被添加到数据库中。

The issues is the HttpPost action gets called twice causing two entries getting added in the database.

如何防止2个动作?

推荐答案

问题是因为您每次单击按钮时都会向表单添加 submit()处理程序,因此第二次提交表单时,它会两次触发您的操作,第三次click意味着三个帖子,依此类推。

The problem is because you are adding a submit() handler to your form every time you click the button, therefore the second time you submit the form, it'll hit your action twice, the third click means three posts, and so on.

要解决此问题,请修改代码以挂钩 click()提交按钮,或者只有表单的 submit()。我的偏好是表单提交。试试这个:

To fix this, amend your code to hook to either the click() of the submit button, or the submit() of the form only. My preference is the form submission. Try this:

$("form").submit(function(e) {
    e.preventDefault();
    $.ajax({
        url: 'EditEntryInline',
        type: 'POST',
        data: $(this).serialize(),
        success: function(result) {
            if (result.success) {
                window.location.reload();
            }
            else {
                // inform the user that the save didn't work
            }
        }
    });
});

另外,你应该修改你的选择器以使用 id 以便此代码不会连接到页面上显示的每个表单的 submit()事件。

Also, you should probably amend your selector to use an id so that this code won't hook up to the submit() event of every form which appears on your page.

这篇关于控制器的HttpPost动作被击中两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆