5

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?

2
  • How does it not work? The new fields aren't validated? Nothing is validated? Where is the validation code? In the partial? In the containing page? A little more code and explanation would be helpful. Commented Apr 19, 2010 at 12:04
  • tvanfosson, I have model with [Required] attribute. In common scenario (without AJAX, just Html.RenderPartial) client validation works fine - if I type empty string in textbox and focus to another textbox, I get validation message. But with AJAX - I don't get this message. Commented Apr 20, 2010 at 4:55

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

jQuery.validate can't see my model. I want to define validation rules in model classes.
You can do so. Check the ASP.NET MVC Futures aspnet.codeplex.com/releases/view/41742
0

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

1 Comment

Rafael Mueller, thank you for your answer, but it's doesn't help me. I have included alert('scripts test') into my partial view - it works. But I still have a problems with validation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.