To make unobtrusive validation work in asp.net mvc3 you have to use the html helper @Html.BeginForm() as mentioned in this very good post : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html.
Without using the helper unobtrusive validation will not be triggered. I could verify that.
Can you explain me what does the helper @Html.BeginForm() do to allow unobtrusive validation to be triggered when the form is submitted ?
Can you also explain me how could I do that manually (read allow unobtrusive validation without calling the @Html.BeginForm()) ?
Please note that I know I can call unobtrusive validation using $("#myform").valid() but I would like to know the magic behind the helper and how to reproduce it.
When you call
BeginForm(see http://j.mp/WrmAyk for theFormExtensionsclass), a newMvcFormobject is created.If you look in the constructor of this class (see http://j.mp/Wrml6F for the MvcForm class) you will see that it creates a new
FormContextobject:_viewContext.FormContext = new FormContext();.When an input, textarea or select is rendered using the HTML helper, the following is called:
tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));, which takes care of rendering the validation attributes from the model metadata.This
GetUnobtrusiveValidationAttributesmethod (see http://j.mp/Wrn4oa for the HtmlHelper class) checks to see if the FormContext is null before rendering attributes:This is why no validation attributes are rendered unless you are within a form. You can get round this by creating a ‘fake’
FormContext, like @karaxuna suggests.