MVC3 Ajax partial view validation

by trouf on 5/05/2011

Ran into a wall of trouble after getting Ajax to work properly in my previous post. Turns out that validation rules are not applied to partial views loaded with Ajax (Even when using the provided Ajax.ActionLink helper).

Thanks to this excellent blogpost http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/ i managed to work it out. But not until after bashing my head against the wall until numb.

The main problem was not so much the actual validation scripts, it was pretty clear to me that the validation rules would have to be rebuilt after injecting new objects into the DOM, but the fact that MVC refused to acually render the data-val / data-val-required properties for the elements that needed validating.

These properties are usually rendered by Html.EditorFor / ValidationMessageFor when used as in the example above.

This is how it should look:

<input class="text-box single-line" 
       data-val="true" 
       data-val-required="This field is required!" 
       id="Property" 
       name="Property" 
       type="text" 
       value=""
/>

But when including a partial view through Ajax inside this outer form, the ability to use BeginForm inside that partial view is lost due to the fact that we can not have nested forms. And without BeginForm, no data-val properties 🙁

The key to getting the partial view to render the properties was to wrap the contents like the following code snippet:

@using(new MvcForm(ViewContext))
{
    <div class="editor-label">
        @Html.LabelFor(model => model.Property)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Property)
        @Html.ValidationMessageFor(model => model.Property)
    </div>

}    

And then to get the validation going, call xhalent’s brilliant js-function after appending the results of the Ajax request to the DOM.

$('#ajaxstuff').ajaxLink({              
  data: {},
  success: function (data) {             
    $('#ajaxdiv').append(data);
    $.validator.unobtrusive.parseDynamicContent('form');
  }
});

stefan.pataky@gmail.com

There is 1 comment in this article:

  1. 13/05/2011SteveiG says:

    Thanks for this, saved me lots of time !!!

Write a comment: