MVC不引人注目的验证。如何使用toastr消息插件显示验证消息

时间:2016-10-05 16:23:25

标签: jquery asp.net-mvc validation unobtrusive-validation

我有简单的Ajax表单

<script type="text/javascript">
        function customSubmit() {
            var form = $("#signup-form");
            if (!ValidateForm(form))
                return;
            $.ajax({
                type: 'POST',
                url: "@Url.Action("SignUpForFree")",
                data: form.serialize()
            });
        }
    </script>
function ValidateForm(form) {
    $.validator.unobtrusive.parse(form);
    var validator = form.validate();
    if (!form.valid()) {
        //some code here to display error message
        return false;
    }
    return true;
}

和JS验证表单以及它是否无效 - 在消息窗口中显示消息:

{{1}}

但是当我提交表格时 - 我有2个提交,一个接一个地发生。 如何阻止第二次提交或如何覆盖标准验证过程?

2 个答案:

答案 0 :(得分:0)

我没有测试代码,所以不确定它是否编译。但是下面应该给你一个想法。我还假设你已经在bundleconfig.cs中包含了toastr.js

@using (Ajax.BeginForm("SignUpForFree", null, new AjaxOptions()
    {
        InsertionMode = InsertionMode.Replace, OnSuccess = "customSubmitSuccess(data)"
    }, new { id = "signup-form" }))
    {
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email)
        <input type="submit" value="CREATE FREE ACCOUNT" />
    }

<script type="text/javascript">

        function customSubmitSuccess(result) {
            if (result.success) {
                // do something when it is success
            } else {
                var formErrors = [];
                $.each(result.errors, function (key, val) {
                    var container = $('span[data-valmsg-for="' + key + '"]');
                    container.removeClass("field-validation-valid").addClass("field-validation-error");
                    container.html(val[val.length - 1].ErrorMessage);

                    formErrors.push(key + "    :  " + val[val.length - 1].ErrorMessage);

                });
                toastr.error(formErrors.join(", "));
            }
        }

        $(function () {
            //allow validation framework to parse DOM
            $.validator.unobtrusive.parse('form');
        });
</script>

答案 1 :(得分:0)

我找到了问题的答案。 这是表格

@using (Ajax.BeginForm("SignUpForFree", null, new AjaxOptions()
    {
        InsertionMode = InsertionMode.Replace
    }, new { id = "signup-form" }))
    {
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email)
        <input type="submit" value="CREATE FREE ACCOUNT"/>
    }

这个如何在验证失败时挂钩,并为此添加自己的处理程序作为存在的附加:

<script type="text/javascript">
        $(document).ready(function () {
            $('#signup-form').bind('invalid-form.validate', function (form, validator) {
                showErrorMessagesOnValidate(validator.errorList);
            });
        });
    </script>

这是一个函数,它将显示带有验证错误的toastr.js消息:

showErrorMessagesOnValidate = function(errors) {
    if (!errors)
        return;
    var toastrObj = {
        ToastMessages: []
    };
    errors.forEach(function(item) {
        var label = $(item.element.labels[0]).text();
        var msg = {
            Title: label,
            Message: item.message,
            Type: "Warning"
        };
        toastrObj.ToastMessages.push(msg);
    });
    displayMessages(toastrObj);
}
function displayMessages(toastrObj) {
    $.each(toastrObj.ToastMessages, function (idx, msg) {
        toastr[msg.Type.toLowerCase()](msg.Message, msg.Title, {});
    });
}

感谢CodeProject Modify jQuery validation settings using MVC unobtrusive validation

中的文章