I wanted to share this quick, but simple, tip on how to use unobtrusive jQuery validation with ASP.NET MVC 3 and forms loaded via AJAX. It’s easy to do, but it’s not entirely intuitive without looking into jquery.validation.js.
All the steps for setting up the validation are the same. I’ll reiterate them here for consistency.
You must also include the correct scripts. Note that, at this time, jquery.validate works only with jQuery 1.4.4. (Nick Craver has pointed me to a version that works with jQuery 1.5 but has not yet been officially released.)
The last bit of setup occurs in the HTML. You need a place to put your dynamic form as well as a wrapper around the entire content so you can parse the form later for validation.
That’s all the setup that is required. Now, go to the location where you are loading a view (a partial view in my specific case) via AJAX. In my particular case, I was loading a partial view based on what node was selected in jsTree. In either case, I am using jQuery’s $.ajax function. Here is the function call:
Without going into too much detail (please see the above link for more information about the
$.ajax function), I am basically doing a GET on the URL /Home/TreeNode and passing in the parameter ‘id’ (which is what I use to look up the data in a simple database).
The interesting part of this code occurs in the success function. There are two things happening here. First, I am placing the data I receive (which is my partial view) into #ajaxcontent. That is simple enough. The second part, and focus of this post, is highlighted at line 9 in the code above. This line is called to give jquery.validate the ability to respond to changes in the form that was loaded via AJAX. Note that any form loaded normally (on the initial page load) will work automatically. You have to call the above line only if you are loading a form after the fact.
That’s all there really is to it! Very easy to do although, as I said previously, not entirely obvious at first glance.