bootstrap 模态中的 MVC 动态验证不阻塞提交

MVC dynamic validation in bootstrap modal not blocking submit

我有一个动态表单(bootstrap 模态),我想在其中使用数据验证。

因此,当显示模式时,我在我的脚本中应用了验证器。 这是我在索引页中的 jquery/javascript 代码,用于显示模态

$("#btnCreate").on("click", function (e) {
    // hide dropdown if any
    $(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
    $('#myModalContent').load(this.href, function () {
        $('#myModal').modal({
            /*backdrop: 'static',*/ 
            keyboard: true
        }, 'show');

        $('#myModal').on('shown.bs.modal', function () {
            $('.chzn-select', this).chosen({ width: "inherit", disable_search: true });
            /*$("form").data("validator", null);
            $.validator.unobtrusive.parse($("form"));*/
            var form = $("form") //use more specific selector if you like
            form.removeData("validator").removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse(form);
        });

        bindForm(this);
    });
    return false;
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    //Refresh
                    location.reload();
                } else {
                    $('#myModalContent').html(result);
                    bindForm();
                }
            }
        });
        return false;
    });

验证成功,但问题如下: 所以当我点击提交按钮时,没有填写必填字段的表单仍然提交。而不是阻止 POST 并告诉用户出了什么问题。

这是我创建的视图:

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @class="horizontal-form"})) { 
@Html.ValidationSummary(false)
<div class="modal-body">
<fieldset>
    <div class="form-group">
        <div class="editor-label">
            @Html.LabelFor(model => model.Naam)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Naam, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Naam)
        </div>
    </div>
    <div class="form-group">
        <div class="editor-label">
            @Html.LabelFor(model => model.Omschrijving)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Omschrijving, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Omschrijving, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="modal-footer">
        <input type="submit" id="verstuurFormulier" value="Create" class="btn btn-primary" />
    </div>
</fieldset>
</div>
}

我认为问题可能在于:

$("form").data("validator", null);

我通常使用这个小片段(在 Whosebug 上找到的 ofc,但我不记得归功于谁 :( )

(function ($) {
    $.validator.unobtrusive.parseDynamicContent = function (selector) {
        //use the normal unobstrusive.parse method
        $.validator.unobtrusive.parse(selector);

        //get the relevant form
        var form = $(selector).first().closest('form');

        //get the collections of unobstrusive validators, and jquery validators
        //and compare the two
        var unobtrusiveValidation = form.data('unobtrusiveValidation');
        var validator = form.validate();

        $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
            if (validator.settings.rules[elname] == undefined) {
                var args = {};
                $.extend(args, elrules);
                args.messages = unobtrusiveValidation.options.messages[elname];
                //edit:use quoted strings for the name selector
                $("[name='" + elname + "']").rules("add", args);
            } else {
                $.each(elrules, function (rulename, data) {
                    if (validator.settings.rules[elname][rulename] == undefined) {
                        var args = {};
                        args[rulename] = data;
                        args.messages = unobtrusiveValidation.options.messages[elname][rulename];
                        //edit:use quoted strings for the name selector
                        $("[name='" + elname + "']").rules("add", args);
                    }
                });
            }
        });
    }
})($);

然后只需删除表单验证器上的 null 并将解析调用更改为:

$.validator.unobtrusive.parseDynamicContent('form');

希望对您有所帮助。

您没有阻止正常提交的发生:

function bindForm(dialog) {
    $('form', dialog).submit(function (e) {
        e.preventDefault();
        $.ajax({
           ...

这意味着您必须手动决定何时提交。我在我的一些项目中使用了以下内容:

$('#myForm').removeData("validator");
$.validator.unobtrusive.parse($('#myForm'));
if ($('#myForm').valid()) { 
    $('#myForm').submit(); 
}
return false;