开发者

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').开发者_如何学Pythonhtml(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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜