jquery client side validation not working in MVC3 partial view
Solution 1:
Any ideas?
Yes, the very first thing you should do is to get rid of all those <script>
tags from your partial view. Partial views should not contain any scripts. Partial views should contain only markup. I have repeated this many times and still see people putting scripts in-there. Scripts should be registered either in your Layout or the main View in which you have rendered the partial, probably by overriding some scripts section registered in your Layout so that all scripts get inserted into the end of your HTML document, just before the closing </body>
tag. That's where they belong.
OK, now to the actual problem: unobtrusive validation doesn't work out-of-the-box with dynamically added elements to the DOM - such as for example sending an AJAX request to the server which returns a partial view and this partial view is then injected into the DOM.
In order to make it work you need to register those newly added elements with the unobtrusive validation framework. To do this you need to call the $.validator.unobtrusive.parse
on the newly added elements:
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
You should put this code inside the AJAX success handler that is injecting the partial into your DOM. Once you have injected the new elements simply call this function.
And if you are not writing your AJAX requests manually with jQuery ($.ajax, $.post, ...) but are relying on some Ajax.BeginForm and Ajax.ActionLink helpers do the job for you, you will need to subscribe to the OnSuccess callback in the AjaxOptions and put this code in there.