MVC 4 client side validation not working for the f

2020-05-19 06:32发布

问题:

I have an Admin page in which the user clicks on links and the corresponding PartialView, containing a web form is then loaded inside a particular div on the Admin page using Ajax.

All of the

"~/Scripts/jquery-2.0.3.js",
"~/Scripts/jquery.unobtrusive-ajax.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"

are referenced within the Admin page and when the PartialView is loaded, the jQuery client side validation won't work.

but when I reference those scripts within the PartialView, everything works just fine but I don't intend to do this for each PartialView because they are numerous and each time each one loads, at least two of those .js files must be requested from the server again.

Is there any way I can have those scripts inside my parent (Admin) page without this issue ?

回答1:

You need this on each one of your partial views:

$(document).ready(function () {

    $.validator.unobtrusive.parse("#YourFormID");

});

Basically the validation is not bound on the dynamically rendered form...



回答2:

Basically the validator parses the elements on document ready. You can call it on your own if you like, however someone has already posted a question about this. and the accepted answer probably still works. One of the answers has a blog post link for further reading if you like.

client side validation with dynamically added field