Thursday, May 7, 2015

Client validation after PartialView loaded via Ajax

I came across this scenario whereby my main View uses Ajax posts to retrieve PartialViews and delivers the markup of the PartialView into my View. I use the jQuery validation framework to implement client side unobstrusive validation.
When I tried to validate my form that had been loaded into the page via an Ajax call, the validation did not appear to be working, my form simply posted. As it turns out, the unobstrusive jQuery validator library parses the markup of a page after it has finished loading for all the validation rules on the page. The result is, jQuery doesn’t know that the dynamically added markup has any validation rules resulting in no validation errors being thrown on post.

Solution
Luckily there is a method that is publicly accessible in the unobstrusive jQuery library which you can call, which will force the parser to scan the markup you just loaded. To do this you need to add the following code to the PartialView (or other dynamically loaded content)
//this code goes in your partialview
$(function(){
//allow the validation framework to re-parse the DOM
jQuery.validator.unobtrusive.parse();
//or to give the parser some context, supply it with a selector
//jQuery validator will parse all child elements (deep) starting
//from the selector element supplied
jQuery.validator.unobtrusive.parse("#formId");
});

 Then in your parent page you can handle the form submission and check the form is valid like this;
 
//then in your parent page handle the form submission
$(function(){
$("#SubmitButton").click(function(){
if (!$("#Form1").valid()){
return false;
}
});
});

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More