MVC client validation after PartialView loaded via Ajax MVC3中 弹出 Dialog时候 提交的时候 使用 Jquery 不验证 form表单 的解决办法

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)

12345
//this code goes in your partialview
$ ( function (){
//allow the validation framework to re-prase the DOM
jQuery . validator . unobtrusive . parse ();
});
view raw gistfile1.js This Gist brought to you by GitHub.       

Then in your parent page you can handle the form submission and check the form is valid like this;

12345678
//then in your parent page handle the form submission
$ ( function (){
$ ( "#SubmitButton" ). click ( function (){
if ( ! $ ( "#Form1" ). valid ()){
return false ;
}
});
});

你可能感兴趣的:(validation)