ASP.NET MVC 3.0 Partially inside and outside the form with unobtrusive data validation attributes

I have with conditional content, according to conditions using jQuery, I include or exclude these parts from form elements.

Here are my functions:

function MoveInsideForm(id) { $("#" + id).insertAfter("#myForm") } function MoveOutsideForm() { $("#myPartial1").insertAfter("#element-outside-from"); $("#myPartial2").insertAfter("##element-outside-from"); } 

The problem is insertAfter() , it does not receive copied custom HTML 5 attributes

For example, I have such an element

 <input data-val="true" data-val-required="*" id="MyInput" name="MyInput" type="text" value="" class="input-validation-error"/> 

But insertAfter() copies it like this:

 <input id="MyInput" name="MyInput" type="text" value=""/> 

Is it possible to specify insertAfter() to copy HTML 5 attributes? My jQuery version 1.6.1.

UPDATE:

Thanks guys for the comments. This is what I do when I process my partial parts inside the form that are generated using unobtrusive data attributes, but if I pass my partial data outside the form, unobtrusive data attributes will not initially be included in the inputs.

So, when I get partial elements outside the form, they initially do not contain data attributes. So this is not a problem with jQuery insertAfter() , is this the nature of the unobtrusive data validation attributes?

+4
source share
1 answer

To create an unobtrusive check, MVC must have a FormContext . When you place an HtmlHelper outside of Html.BeginForm or Ajax.BeginForm , HtmlHelpers will not have unobtrusive validation attributes unless you manually create an instance of FormContext. You can manually create an instance of FormContext by pasting the following code in front of your helpers:

 this.ViewContext.FormContext = new FormContext(); 

If you place your helpers before BeginForm (), then be sure to clear the FormContext after your helpers and before the start of the form.

+6
source

All Articles