Friday, March 16, 2012

ASP.NET MVC 3: ViewContext.FormContext

ASP.NET MVC 3 introduced the concept of unobtrusive client validation. Based on data annotations on top of your model,  the HTML helpers render markup with validation info using the HTML5 data attribute:
<input data-val="true" 
data-val-required="The ProductName field is required."
id="ProductName" name="ProductName" type="text" />

These data attributes are picked up by the jquery.validate.unobtrusive library that constructs the correct validation rules for jquery.validate.

In our project, we load some parts of the user interface dynamically based on some user actions. We noticed that the MVC framework didn’t render the data attributes in that case.

What’s the reason? We found out attributes with validation rules are rendered only if the ViewContext.FormContext property is initialized. It could be done with Html.BeginForm() method called in the beginning but, as in our case there was already a form on the page, so we set the FormContext manually:

if (ViewContext != null && ViewContext.FormContext == null)
 var dummyFormContext = new FormContext();
 ViewContext.FormContext = dummyFormContext;

No comments: