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 () {
        $.validator.unobtrusive.parse("#myDiv");
    });
</script>

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.

Advertisements
Tagged , , ,

One thought on “MVC Validation 3: Unobtrusive validation in Ajax-loaded partial views

  1. Prakash says:

    Hi, Thanks a Lot, This bit of Code Works Great….:)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: