引导模式中的MVC动态验证不阻止提交

时间:2015-04-15 13:43:34

标签: javascript jquery asp.net-mvc twitter-bootstrap-3 unobtrusive-validation

我想要使用数据验证的动态表单(bootstrap modal)。

因此,当显示模态时,我在我的脚本中应用验证器。 这是我在索引页面中的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>
}

2 个答案:

答案 0 :(得分:1)

您并未停止发生正常提交:

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;

答案 1 :(得分:0)

我认为问题可能在于:

  

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

我通常使用这个小片段(在StackOverflow上找到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');

希望这有帮助。