I\'m trying to enable unobtrusive javascript validation for dynamically created items. The problem with javascript was already solved in another SO question and this is not the
You could manually fake a form context. For example if you had some partial view which doesn't contain a element and which is called using AJAX to regenerate some input elements you could do this:
@model MyViewModel
@{
ViewContext.FormContext = new FormContext();
}
@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
The corresponding input elements will now posses the data-*
attributes. But that might not be enough. If you are only refreshing (using AJAX) only a portion of the but not actually replacing the form element in the DOM calling
$.validator.unobtrusive.parse
wouldn't suffice. You need to remove any previous validations associated to this element:
success: function(result) {
// we are replacing only a portion of the form
$('#somePartOfTheForm').html(result);
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
}