Alex Rivera | Logout

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

Asked 2011-09-20T15:31:06.837
11

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
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"         type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
    $(".phoneMask").mask("(999) 999-9999");
});
</script>

@{
    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)
<table>
    <tr>
        <td style="width:200px;">City*</td>
        <td>State</td>
        <td>Zip/Postal Code</td>
    </tr>
    <tr>
        <td>@Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 })</td>
        <td>
        @Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode
                                 , MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))</td>
        <td>
        <
Edit
Report

1 Answer

9

If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:

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

You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:

$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");
answered 2012-02-07T18:39:06.293

Your Answer