jQuery.Validation.Unobtrusive客户端验证,只有当脚本视图页面上工作 [英] jQuery.Validation.Unobtrusive client side validation only works when scripts are on view page

本文介绍了jQuery.Validation.Unobtrusive客户端验证,只有当脚本视图页面上工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET MVC应用程序4 使用在 jQuery.validation.js 插件和MVC的 jQuery.validation.unobtrusive.js 。我用我的看法模型数据注解来验证文本框的输入是一个整数。

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

 <%Html.RenderPartial(新); %GT;

其中第一inital页面加载,客户端验证工作。但随着一个Ajax调用嵌套视图的任何重新加载,客户端验证不再起作用。这是为什么?

更新:(code从例如 webdeveloper的的下方溶液)

  $ validator.unobtrusive.parse($('形式'));

例如:

  VAR saveAndUpdate =功能(URL){
    VAR myForm会= $('形式',$('#TheDivThatContainsTheNewHTML'));
    $阿贾克斯({
        网址:网址,
        输入:POST,
        数据:myForm.serialize(),
        成功:函数(结果){
            $('#TheDivThatContainsTheNewHTML')HTML(结果)。
            $ .validator.unobtrusive.parse($('#TheDivThatContainsTheNewHTML'));
        },
        错误:功能(XHR,ajaxOptions,thrownError){
            警报(xhr.status);
            警报(thrownError);
        },
        数据类型:HTML
    });
}


解决方案

但是,随着Ajax调用嵌套视图的任何重新加载,客户端验证不再起作用。这是为什么?

验证适用于文件准备好,当您耳目一新页面,你应该手动初始化验证你的形式。

这样的:

  $ validator.unobtrusive.parse(形式);

同样的问题:<一href=\"http://stackoverflow.com/questions/4406291/jquery-validate-unobtrusive-not-working-with-dynamic-injected-elements\">jquery.validate.unobtrusive不使用动态元素的注入工作

I have an ASP.NET MVC 4 App that uses the jQuery.validation.js plugin and MVC's jQuery.validation.unobtrusive.js. I use data annotations on my view model to validate a textbox's input to be an integer.

This (nested) view is loaded within a parent view using...

<% Html.RenderPartial("New"); %>

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

Update: (Code example from webdeveloper's solution below)

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

Example:

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'
    });
}

解决方案

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

Validation applies on document ready, when you refreshing page you should manually init validation for your form.

Like this:

$.validator.unobtrusive.parse("form");

Same question: jquery.validate.unobtrusive not working with dynamic injected elements

这篇关于jQuery.Validation.Unobtrusive客户端验证,只有当脚本视图页面上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆