Arno 2501
Arno 2501

Reputation: 9397

Why unobtrusive validation wont work in asp.net mvc3 without using @Html.BeginForm()

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.

Upvotes: 2

Views: 931

Answers (2)

Ian Routledge
Ian Routledge

Reputation: 4042

When you call BeginForm (see http://j.mp/WrmAyk for the FormExtensionsclass), a new MvcForm object 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 FormContext object: _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 GetUnobtrusiveValidationAttributes method (see http://j.mp/Wrn4oa for the HtmlHelper class) checks to see if the FormContext is null before rendering attributes:

FormContext formContext = ViewContext.GetFormContextForClientValidation();
if (formContext == null)
{
    return results;
}

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.

Upvotes: 2

karaxuna
karaxuna

Reputation: 26930

Write this in your view and it will work:

 ViewContext.FormContext = ViewContext.FormContext ?? new FormContext();

When code is inside @Html.Beginform (in the same view), then html element validation attributes are got from metadata, In other case, it is not.

Upvotes: 2

Related Questions