小编典典

无法在jQuery Ajax Post上使用MVC 3进行无干扰的验证

ajax

我很难在MVC3上进行验证。当我直接加载页面时,它工作正常,但是当我使用jquery AJAX POST时,它无法验证:

使用加载此表单$('#modal-dialog').load('/DartsMVC/Restaurant/Edit/13'),这是呈现的HTML:

<form action="/DartsMVC/Restaurant/Edit/13" method="post">
    <fieldset>
        <legend>Restaurant</legend>

        <input data-val="true" data-val-number="The field RestaurantID must be a number." data-val-required="The RestaurantID field is required." id="RestaurantID" name="RestaurantID" type="hidden" value="13">

        <div class="editor-label">
            <label for="Name">Name</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="furaibo">
            <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
        </div>

        <p>
            <input type="submit" value="Save" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false">
        </p>
    </fieldset>
</form>

通过拦截表单/提交来使用AJAX POST。帖子完成后,将弹出并关闭模式对话框。我想在发送帖子之前验证表格:

// force change the submit data to an ajax POST (usually 'save', 'delete' button)
$('#modal-dialog').delegate('form', 'submit', function (e) {
    e.preventDefault();
    var form = $(this);
    form.validate(); // does nothing
    if (form.valid()) {
        $.ajax({
            url: form.attr('action'),
            type: "POST",
            data: form.serialize(),
            success: function (data) {
                $('#modal-dialog').dialog('close');
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
            }
        });
    }
});

我这样做是否破坏了某些东西? .valid()始终返回true。

我的web.config具有:

  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

我的页面来源有:

<link href="/DartsMVC/Content/themes/cupertino/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css">

<script src="/DartsMVC/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>

<script src="/DartsMVC/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>

我的模型有:

    [Required]
    public string Name { get; set; }

经过更多研究,我认为它可能与动态控件有关:


阅读 254

收藏
2020-07-26

共1个答案

小编典典

解决了

调用$ .validator.unobtrusive.parse($(’form’))可以达到目的。我想需要为动态内容重新创建验证器

2020-07-26