Confirmation to pause form submit until Ok has bee

2019-03-03 10:04发布

I have a form that a confirmation dialog pops up (do you want to continue) right now it pops up but the form is being sent to my controller at the same time, which begins processing regardless if you hit yes or no. How do I pause the form submit until after the javascript confirmation has been shown/selected.

 @using (Html.BeginForm("Process", "Home", FormMethod.Post, 
 new { id ="MyForm" })) {  
    @Html.TextBoxFor(m => m.Name); 
    // other form controls...
    <input id="Submit" type="submit" value="Apply Changes" /> 
 }

javascript: (using jquery-ui)

 $(function () {
        $("#Confirm").dialog({
            autoOpen: false,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                    $('#MyForm').submit();
                    return true;
                },
                Cancel: function() {
                    $(this).dialog("close");
                    event.preventDefault();
                    return false;
                }
            }
        });

        $("#Submit").click(function () {
            $("#Confirm").dialog("open");
        });
    });

3条回答
闹够了就滚
2楼-- · 2019-03-03 10:43

Prevent the default action immediately, then trigger the submit on the ok button press.

 $(function () {
    $("#Confirm").dialog({
        autoOpen: false,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
                $('#MyForm')[0].submit();
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        }
    });

    $("#MyForm").submit(function (e) {
        e.preventDefault();
        $("#Confirm").dialog("open");
    });
});
查看更多
何必那么认真
3楼-- · 2019-03-03 10:44

Move the submit button outside of the form and change it to a regular <input type="button"/>.

Your modal "OK" function does the submit for you, so you don't need a submit button in the form.

@using (Html.BeginForm("Process", "Home", FormMethod.Post, 
 new { id ="MyForm" })) {  
    @Html.TextBoxFor(m => m.Name); 
    // other form controls...

 }
<input id="Submit" type="button" value="Apply Changes" /> 
查看更多
对你真心纯属浪费
4楼-- · 2019-03-03 11:07

You can also use the "onsubmit" event of the form itself and return either true or false if you want it to actually submit data or not.

查看更多
登录 后发表回答