简体   繁体   中英

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?

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM