Ok, here is the deal, I have seen a few posts on SO relating to this issue, but nothing is working for me.
Basically, I have select drop downs that are being load
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 could only get it the validation to work inside of OnComplete
instead of OnSuccess
:
Here's the AJAX Code:
@using (Ajax.BeginForm("Index", null,
new AjaxOptions { OnSuccess = "onSuccess",
OnComplete = "onComplete"},
new { id = "mainForm" }))
And here's my script:
function onComplete(result) {
$.validator.unobtrusive.parse("#mainForm");
alert("Complete");
};
$.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 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);
});
}
});
Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call
this.ViewContext.FormContext = new FormContext();
Reference