Client Side Validation After Ajax Partial View Result in Asp Net Mvc 3

Now, as ASP.NET MVC 3 beta was finally released I have decided to give it a try. The most exciting thing that I have noticed is implementation of an idea of so called Unobtrusive JavaScript. This is for both Ajax helpers and Client Validation. And I have to admit that I just love it. I wll just copy and paste text from scottgu blog:

Unobtrusive JavaScript and HTML 5: The AJAX and Validation helpers in ASP.NET MVC now both use an unobtrusive JavaScript approach by default. Unobtrusive JavaScript avoid injecting inline JavaScript into HTML, and instead enables cleaner separation of behavior using the new HTML 5 data- convention (which conveniently works on older browsers as well). This makes your HTML smaller and cleaner, and makes it easier to optionally swap out or customize JS libraries. The Validation helpers in ASP.NET MVC 3 also now use the jQueryValidate plugin by default.

Basically we get all the validation done by loading js function parsing loaded DOM searching for specific parameters based on which validation rules are applied to elements. And all of that without a single js line from ‘our’ - web developers side. One thing is not obvious though and it certainly needs extra explanation: what happens after part of the page is loaded via Ajax request (common Partial View result). Validation is not turned for those elements although all attributes are correctly marked. I have dig a little and found within JavaScript file ‘jquery.validate.unobtrusive.js’ function: jQuery.validator.unobtrusive.parse(selector). Calling function after new content is loaded solves problem, like in the example below:

$.post("test/updateCustomer", { name: "Mark", surname: "Barker" },
  function(htmlContent){
    $('#container').html(htmlContent);
    jQuery.validator.unobtrusive.parse('#content')
  }
);

Hope it helps someone…

comments powered by Disqus