MVC3 Unobtrusive Validation Not Working after Ajax Call MVC3 Unobtrusive Validation Not Working after Ajax Call ajax ajax

MVC3 Unobtrusive Validation Not Working after Ajax Call


$.validator.unobtrusive.parse("#frmAddItem"); will work. Do note that it must be in the partial that you load through ajax (below the form in the partial)

<form id="frmAddItem" method="POST" action="...">    <!-- all the items --></form><script type="text/javascript">    $.validator.unobtrusive.parse("#frmAddItem");</script>


I'm adding my experience as the above recommendations did not work for me.This solution did and may help others that get directed to this page from a search engine:

Add OnSuccess="$.validator.unobtrusive.parse('YourFormName');" to you AjaxOptions

An example using Ajax.ActionLink:

@Ajax.ActionLink("This is a test to get unobtrusive javascript working",                 "Name_of_your_controller_action",                 new AjaxOptions { HttpMethod = "POST",                                    InsertionMode = InsertionMode.Replace,                                    UpdateTargetId = "UserDiv",                                    OnSuccess="$.validator.unobtrusive.parse('UserDetailsForm');"                                   }                )

This solution was found at:http://blog.janjonas.net/2011-07-24/asp_net-mvc_3-ajax-form-jquery-validate-supporting-unobtrusive-client-side-validation-and-server-side-validation


I wrote this little snippet that will you can place in your javascript file and it will handle all your forms that are ajax loaded.

//enable unobtrusive validation for ajax loaded forms$(document).ajaxSuccess(function (event, xhr, settings) {    //process only if html was returned    if ($.inArray('html', settings.dataTypes) >= 0) {        //will parse the element with given id for unobtrusive validation        function parseUnobtrusive(elementId) {            if (elementId) {                $.validator.unobtrusive.parse('#' + elementId);            }        }        //get the form objects that were loaded.  Search within divs        //in case the form is the root element in the string        var forms = $('form', '<div>' + xhr.responseText + '</div>');        //process each form retrieved by the ajax call        $(forms).each(function () {            //get the form id and trigger the parsing.            //timout necessary for first time form loads to settle in            var formId = this.id;            setTimeout(function () { parseUnobtrusive(formId); }, 100);        });    }});