HttpPost action of a controller gets hit twice

假如想象 提交于 2019-12-07 12:30:26

问题


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.

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

How can I prevent the 2 actions?


回答1:


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.

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
            }
        }
    });
});

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.




回答2:


You're wiring up another one ajax submit on your actual form submit. Consider to put return false; at the end.



来源:https://stackoverflow.com/questions/12722971/httppost-action-of-a-controller-gets-hit-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!