griZZZly8
griZZZly8

Reputation: 694

ASP.NET MVC client validation with partial views and Ajax

I'm using the client validation function of the MVC 2.0 framework (with Html.ValidationMessageFor() and Html.EnableClientValidation()).

Everything is nice, when I use the validation in a simple form.

But when I get this form via jQuery Ajax

$.get('PathToMyForm', function(htmlResult) {
    $('selector').html(htmlResult);
});

client validation doesn't work. Why?

Upvotes: 5

Views: 5698

Answers (3)

JasCav
JasCav

Reputation: 34632

If you are using jquery.validate (particularly with MVC) and you are loading pages via AJAX, you need to make the following call after the page loads:

$.validator.unobtrusive.parse($("#validation"));

See more at my blog post: Using Unobtrusive jQuery Validation with Forms Loaded via AJAX

Upvotes: 7

Rafael Mueller
Rafael Mueller

Reputation: 6083

Maybe jQuery isn't evaluating the JavaScript code on the Ajax response?

Try using dataType property on the Ajax call,

$.get('PathToMyForm', {dataType 'html'}, function(htmlResult) {
    $('selector').html(htmlResult);
});

From the jQuery documentation:

dataType Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Upvotes: 0

Atanas Korchev
Atanas Korchev

Reputation: 30671

I've had problems with MVC validation and partial views too. I sorted it out by using jquery.validate.js instead of the build-in client-validation. You can try that out.

Upvotes: 0

Related Questions