Question

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'
    });
}
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top