8

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'
    });
}
Andrei
  • 42,814
  • 35
  • 154
  • 218
duyn9uyen
  • 9,585
  • 12
  • 43
  • 54

1 Answers1

12

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

Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47
  • 1
    Thanks! I also notice that you can resolve this by explicitly adding in the script tags in the nested view, instead of relying on the scripts that are rendered by the Master page. – duyn9uyen Apr 19 '13 at 13:41
  • http://stackoverflow.com/questions/16310448/mvc4-custom-unobtrusive-validator-isnt-working here is good point to check as well – Andrei Jun 18 '13 at 08:13