Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Unobtrusive validation - why form context is needed?

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?

like image 935
kubal5003 Avatar asked Feb 28 '12 12:02

kubal5003


1 Answers

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');   
}
like image 67
Darin Dimitrov Avatar answered Oct 31 '22 23:10

Darin Dimitrov