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 case here.
Dynamic creation of items in this case is just cloning of one empty item that is generated outside of the main form.
The problem is that if I use html helpers like TextBoxFor, CheckBoxFor, ... outside the html form element then attributes required in order for the validation to work (eg. data-val-required
) are not generated.
I've already checked the MVC source code and there is a line that returns empty attribute list if FormContext
is null. (this throws no exceptions)
Why?
You could manually fake a form context. For example if you had some partial view which doesn't contain a <form>
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 <form>
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With