MVC3 Razor Partial view render does not include data- validation attributes

Spread the love

Question Description

I have a farily straight forward form that renders personal data as a partial view in the center of the form. I can not get client side validation to work on this form.
I started chasing down the generate html and came up with the same model field rendered on a standard form and a partial view.

I noticed that the input elements are correctly populated on the first call, @html.partial, the following only happens when the partialview is reloaded via an ajax request.

First the header of my partial view, this is within a Ajax.BeginForm on the main page.

@model MvcMPAPool.ViewModels.EventRegistration




@{
    var nPhn = 0;
    var dTotal = 0.0D;
    var ajaxOpts = new AjaxOptions{ HttpMethod="Post", UpdateTargetId="idRegistrationSummary", OnSuccess="PostOnSuccess" };
    Html.EnableClientValidation( true );
    Html.EnableUnobtrusiveJavaScript( true );
}

Here is the razor markup from the partial view:

@Html.ValidationMessageFor(model=>Model.Player.Person.Addresses[0].PostalCode)
City* State Zip/Postal Code
@Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 }) @Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode , MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))
@Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].PostalCode, new { style="width:80px;", maxlength=10 })

Here is the rendered field from the partial view:

        
        

Here is the same model field rendered in a standard view:

        

Notice that the partial view rendering has no data-val-xxx attributes on the input element.

Is this correct? I do not see how the client side validation could work without these attributes, or am I missing something basic here?

Practice As Follows

In order to create the unobtrusive validation attributes, a FormContext must exist. Add the following at the top of your partial view:

if (this.ViewContext.FormContext == null) 
{
    this.ViewContext.FormContext = new FormContext(); 
}

Leave a Comment