I’m working on an MVC2 application that makes extensive use of forms being sucked into the current page using ajax like this, which issues the request and gets back html representing the form which is then presented in a jQuery UI modal dialog;
I wanted to use the new out of the box validation toolset with data annotations, which on the face of it looks pretty cool, so I followed the guide on getting this working using jQuery validator. Namely, I got myself the MicrosoftMvcJQueryValidation.js from the MvcFutures project and then added data annotations to my view model, eg;
That’s it to get server side validation working, which works a treat, but to get client side working, I then added the following script includes to my master page;
Enabled client validation in my form and added some validation messages;
This little snippet of code is in MicrosoftMvcJQueryValidation.js, which remember we included in our master page (which is rendered in the host page, NOT our partial form view we’re getting using ajax).
That won’t be fired so to get the validation working, we just need to do the same thing right? Not quite. I added the above code to a jQuery startup function in my partial view, it gets called successfully but….nothing, it still didn’t work because window.mvcClientValidationMetadata was undefined. Now the reason is something different – the jQuery startup function is actually invoked before the inline <script></script> block that sets window.mvcClientValidationMetadata!
The way the window.mvcClientValidationMetadata is used can help us though – the inline script pushes the latest validation data for the form onto this variable and the code above pops it back off. As such, we can just interrogate the length of the array when we start up and if there is no data there yet, retry after a short delay. If we keep doing that until it’s been processed all should be well with the world. So, my modified startup script is as follows;
and all is indeed well with the world. I think this should even cover the edge cases where you have multiple forms in your partial view, each with their own validation, but I’ve yet to test it any more thoroughly.