Tag Archives: ajax

MVC Validation 3: Unobtrusive validation in Ajax-loaded partial views

It’s a pretty good idea usually to not reload the entire page, but if you use MVCs now-standard unobtrusive validation you’ll find that the validation does not work on the partial you’ve just loaded.

Here’s how you solve this. Say you have a page which uses a script to load a view using ajax to a div, something like this:

function loadStuff()
    $('#myDiv').load(window.location.pathname + "/Stuff");

If you do this and don’t do anything else, the unobtrusive validation won’t work at all. If you try to brute force your way of of this by including the unobtrusive validation javascripts again on the partial view, the validation will kinda-sorta-work. But really, it doesn’t work. Instead what really want to do is to reparse and rebind the validation. Including this at the bottom of the partial view you want to load will work.

<script type="text/javascript">
    $(document).ready(function () {

I’m not sure if it would be a better fit to place this in the ajax-loader method instead. I think I had some problems with that and went with putting this in the bottom of the page. You can reparse the entire document if you want to no real ill effect, but parsing the div you just loaded is probably more efficient.

There’s nothing more to it really, but it’s a real gotcha that at had me confused at first.

Tagged , , ,