Cameron
Cameron

Reputation: 28853

ASP.NET MVC 3 Validation and AJAX

I have a form that is displayed in a modal using Ajax on my app and this form has validation on it using the built-in validation in MVC 3 (Microsoft use jquery.validate).

However it seems as though BECAUSE the form has been called using ajax the validation logic is no longer talking to each other (much like what happens if you have not used .live() for something that has been appended to the page after the document load.)

How do I get around this problem?

EDIT

I have tried to get this working using: http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/ as provided by 3nigma below, but it doesn't seem to have any effect :/

$.ajax({
                url: $(this).attr('href'),
                success: function (responseHtml) {
                    $('.uiModalContent').html($(responseHtml));
                    $('.uiModalContent').removeClass('loading');
                    // Apply validation to form that is inside the modal
                    $('.AjaxForm').removeData('validator');
                    $.validator.unobtrusive.parseDynamicContent('.AjaxForm input');
                },

I have added the code to my success call on my ajax for showing the modal as I can't put the javascript directly inside the called view as jquery ajax bins off script tags. However it doesn't seem to be applying the validation to the dynamically added fields...

Any help would be much appreciated. Thanks

Upvotes: 2

Views: 913

Answers (2)

Cameron
Cameron

Reputation: 28853

$.validator.unobtrusive.parseDynamicContent('.uiModalContent');

Fixes the problem :)

Upvotes: 0

Christoffer
Christoffer

Reputation: 2125

I have done a similar thing in my project and it "works for me" :)

Perhaps you can try a few things:

  • In $('.uiModalContent').html($(responseHtml)); I dont think you need to wrap responseHtml as a jquery object; in fact it's probably better to just use responseHtml as is: $('.uiModalContent').html(responseHtml);

  • Try changing the validation call to: $.validator.unobtrusive.parse($('.uiModalContent'));

I don't know if it will solve your problem but it's worth a try.

Upvotes: 2

Related Questions