jQuery.Validation.Unobtrusive客户端验证仅在脚本在视图页面上时才有效

duy*_*yen 8 asp.net-mvc client-side-validation asp.net-mvc-validation unobtrusive-validation asp.net-mvc-4

我有一个ASP.NET MVC 4应用程序,它使用jQuery.validation.js插件和MVC的jQuery.validation.unobtrusive.js.我在视图模型上使用数据注释来验证文本框的输入是否为整数.

使用...在父视图中加载此(嵌套)视图

<% Html.RenderPartial("New"); %>
Run Code Online (Sandbox Code Playgroud)

第一个初始页面加载,客户端验证工作.但是任何使用ajax调用重新加载嵌套视图,客户端验证都不再有效.这是为什么?

更新 :(来自webdeveloper解决方案的代码示例)

$.validator.unobtrusive.parse($('form'));
Run Code Online (Sandbox Code Playgroud)

例:

var saveAndUpdate = function (url) {
    var myForm = $('form', $('#TheDivThatContainsTheNewHTML'));
    $.ajax({
        url: url,
        type: 'POST',
        data: myForm.serialize(),
        success: function (result) {
            $('#TheDivThatContainsTheNewHTML').html(result);
            $.validator.unobtrusive.parse($('#TheDivThatContainsTheNewHTML'));          
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        },
        dataType: 'html'
    });
}
Run Code Online (Sandbox Code Playgroud)

web*_*per 12

But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?

验证适用于document ready,当您刷新页面时,您应该手动为表单初始化验证.

像这样:

$.validator.unobtrusive.parse("form");
Run Code Online (Sandbox Code Playgroud)

同样的问题:jquery.validate.unobtrusive不使用动态注入元素