Bill
Bill

Reputation: 2352

ASP.NET MVC 3 not generating validation data attributes

I have a huge Form that I split in terms of Views (Partials) & ViewModels.

The main form view, contains calls to:

@Html.Partial("Educations", @Model)

The partial view, renders itself by looping over @Model, generating a Div row for each record (TextBox not TextBoxFor or any other Html helper).

What happens is that, no validation data attributes are being generated for the partial view.

One note though, once I load the main form view dynamically, I do the following:

(function ($) {

$.fn.updateValidation = function () {
    var form = this.find("form")
        .removeData("validator")
        .removeData("unobtrusiveValidation");

    $.validator.unobtrusive.parse(form);

    return this;
};

})(jQuery);

Also, the partial view contains a button to add more rows. When I add additional rows, those newly added ones are being validated as I inject manually the data validation.

The problem now is that, the rows that are rendered upon loading form are not having any data validation attribute, and hence even calling the above plugin to re-initialize unobtrusive validation, wont help or make any difference.

Thanks

Upvotes: 2

Views: 831

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

Try adding a form context to your partial view:

@model MyViewModel
@{
    ViewContext.FormContext = new FormContext();               
}

...
@Html.EditorFor(x => x.Foo)

If the HTML helpers such as Html.TextBoxFor are not used inside a Html.BeginForm they will not emit the HTML5 data-* attributes. They only emit those attributes if there's a FormContext in scope.

Upvotes: 5

Related Questions