jQuery验证带有Ajax提交的SubmitHandler [英] jQuery Validate SubmitHandler with Ajax Submission Not being hit

查看:123
本文介绍了jQuery验证带有Ajax提交的SubmitHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我想使用ajax将表单提交给控制器.我有这个:

On my view I want to submit the form to the controller using ajax. I have this:

@section scripts{
    @Scripts.Render("~/bundles/jqueryval")

    <script>
        $(document).ready(function() {

            // Mask
            $("#Teu_Rate").mask("####.##", { reverse: true });
            $("#Mcsap_Rate").mask("####.##", { reverse: true });

            // Submission
            var redirectUrl = '@Url.Action("Index", "tblPersonnels")';
            var settings = {};
            settings.baseUri = '@Request.ApplicationPath';
            var infoGetUrl = "";
            if (settings.baseUri === "/Scalehouse") {
                infoGetUrl = settings.baseUri + "/tblPersonnels/Create/";
            } else {
                infoGetUrl = settings.baseUri + "tblPersonnels/Create/";
            }

            // ajax portion
            $("form").validate({
                submitHandler: function(form) {
                    $.ajax({
                        url: infoGetUrl,
                        method: "POST",
                        data: $("form").serialize(),
                        beforeSend: disableCreateBtn(),
                        success: function() {
                            console.log("success");
                            toastr.options = {
                                positionClass: "toast-top-full-width",
                                onHidden: function() {
                                    window.location.href = redirectUrl;
                                },
                                timeOut: 3000
                            }
                            toastr.success("Personnel successfully created")
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            toastr.options = {
                                positionClass: "toast-top-full-width",
                                onHidden: function() {
                                    enableCreateBtn();
                                },
                                timeOut: 3000
                            }
                            var status = capitalizeFirstLetter(textStatus);
                            var error = $.parseJSON(jqXHR.responseText);
                            console.log(error);
                        }
                    })
                }
            });

            function capitalizeFirstLetter(string) {
                return string.charAt(0).toUpperCase() + string.slice(1);
            }

            function disableCreateBtn() {
                $('#Personnel-Create-Btn').prop('disabled', true);
            }

            function enableCreateBtn() {
                $('#Personnel-Create-Btn').prop('disabled', false);
            }
        });
    </script>
}

请求完成并成功完成后,我应该在控制台中收到一条消息,并收到一个Toastr通知,但是我什么都没有收到,也没有收到任何控制台错误,但是正在输入的记录正在输入成功,则表示该表单是通过常规MVC约定提交的.

When the request is done and completed successfully, I should be getting a message in my console and a toastr notification, but I am receiving neither and I'm not receiving any console errors, but the record that I am entering is being entered successfully, so that means that the form is being submitted through regular MVC conventions.

我如何使我的Ajax提交工作正常?

How do I make my ajax submission work?

更新

在下面用Sparky评论后,我将代码更改为:

After commenting below with Sparky, I've changed my code to:

$("form").submit(function (t) {

    t.preventDefault();

        $.ajax({
            url: infoGetUrl,
            method: "POST",
            data: $("form").serialize(),
            beforeSend: disableCreateBtn(),
            success: function() {
                console.log("success");
                toastr.options = {
                    positionClass: "toast-top-full-width",
                    onHidden: function() {
                        window.location.href = redirectUrl;
                    },
                    timeOut: 3000
                }
                toastr.success("Personnel successfully created");
            },
            error: function(jqXHR, textStatus, errorThrown) {
                toastr.options = {
                    positionClass: "toast-top-full-width",
                    onHidden: function() {
                        enableCreateBtn();
                    },
                    timeOut: 3000
                }
                var status = capitalizeFirstLetter(textStatus);
                //var error = $.parseJSON(jqXHR.responseText);
                console.log(jqXHR);
            }
        });

    });

现在,如果表单为空..而我按下了create按钮..某种程度上,ajax进入了成功函数,同时在某些必填字段上给了我验证错误..然后像重定向到另一个页面一样请求成功..有什么想法吗?

Now, if the form is empty.. and I hit the create button.. somehow the ajax is going into the success function while giving me my validation errors on certain fields that are required.. then redirected to another page as if the request was successful.. any ideas?

更新2

我通过使用以下语法使其正常工作:

I got it working by using this syntax:

$("form").data("validator").settings.submitHandler =
    function(form) {
        $.ajax({
            url: infoGetUrl,
            method: "POST",
            data: $("form").serialize(),
            beforeSend: disableCreateBtn(),
            success: function () {
                console.log("success");
                toastr.options = {
                    positionClass: "toast-top-full-width",
                    onHidden: function () {
                        window.location.href = redirectUrl;
                    },
                    timeOut: 3000
                }
                toastr.success("Personnel successfully created.");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                toastr.options = {
                    positionClass: "toast-top-full-width",
                    onHidden: function () {
                        enableCreateBtn();
                    },
                    timeOut: 3000
                }
                var status = capitalizeFirstLetter(textStatus);
                var error = $.parseJSON(jqXHR.responseText);
                console.log(error);

                var modelState = error.modelState;
                //console.log(modelState);
                $.each(modelState,
                    function (key, value) {
                        var id = "";
                        if (key === "$id") {
                            id = "#" + key.replace('$', '').substr(0, 1).toUpperCase() + key.substr(2);
                        } else {
                            //console.log(key);
                            var status = capitalizeFirstLetter(textStatus);
                            toastr.error(status + " - " + modelState[key]);
                        }
                        var input = $(id);
                        //console.log(id); // result is #id
                        if (input) { // if element exists
                            console.log(id);
                            input.addClass('input-validation-error');
                        }
                    });
            }
        });
    }

我不知道为什么,但是它在起作用..我很想听听为什么

I don't know why, but it is working.. I'm interested in hearing why though

推荐答案

我开始使用它,并更新了有关如何..的问题,但是您能解释一下为什么这种语法比其他语法更有效吗?

I got it working and updated my question as to how.. but could you explain why this syntax works over the others?

您的.submit()处理程序不是一个好主意,因为它将干扰jQuery Validate插件处理表单的Submit事件的方式. (基本上,您已经阻止了默认的提交,然后再将其提交给Validate插件.)无论是否使用ASP,这绝对不是这样做的方法. Validate插件为需要捕获此事件的任何目的提供submitHandler功能.

Your .submit() handler is a bad idea because it's going to interfere with the way the jQuery Validate plugin handles the form's submit event. (Basically, you've prevented the default submit and then never turned it back over to the Validate plugin.) ASP or not, this is absolutely not the way to do it. The Validate plugin provides the submitHandler function for any purpose where you need to capture this event.

您的.settings.submitHandler之所以有效,是因为当您无权编写自己的.validate()方法(由于使用Unobtrusive Validation插件)时,这是定义submitHandler函数的唯一方法. 根据文档submitHandler提交表格的正确位置通过Ajax在验证后通过".

Your .settings.submitHandler works because it's the only way to define the submitHandler function when you have no access to write your own .validate() method (thanks to Unobtrusive Validation plugin). As per the documentation, the submitHandler is the "right place to submit a form via Ajax after it is validated".

因此,如果我不使用通用语言,那么我可以使用原始代码吗?

so if I were not to use the unobtrusive, then I could use my original code?

通常在页面加载时通过.validate()方法初始化jQuery Validate插件.此方法只能被调用一次,所有后续调用都将被忽略.当您使用ASP和Unobtrusive Validation插件时,它将为您构造并调用.validate()方法,因此您不再可以通过自己调用.validate()来设置任何选项或规则.

The jQuery Validate plugin is initialized via the .validate() method, normally on page load. This method can only be called one time and all subsequent calls will be ignored. When you use ASP and the Unobtrusive Validation plugin, it constructs and calls the .validate() method for you, therefore you can no longer set any options or rules by calling .validate() yourself.

这篇关于jQuery验证带有Ajax提交的SubmitHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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