jQuery.Validation.Unobtrusive client side validati

2019-02-12 22:06发布

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

1条回答
神经病院院长
2楼-- · 2019-02-12 23:03

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

查看更多
登录 后发表回答