Checking mvc clientside for nested (collection) properties

I am using asp.net mvc 3 with jquery unobtrusive validation. I recently changed from standard DataAnnotations to FluentValidation and it works great.

My main reason for choosing FluentValidation was to check the nested properties on my viewmodel (but I found that there are other interesting reasons for using it) that look like this (ignore the accessors, this is pseudo):

class Vm { string Prop; string AnotherProp; IEnumerable<ElementsVm> Elements; } class ElementsVm { bool Required; string Id; string Title; string Value; } 

Using FluentValidation I am doing a validator for Vm and for ElementVm, and my unit tests are green, showing that server side validation is working.

The client side, "Prop" and "AnotherProp" work - my validation rules also work on the client side, as expected (as with DataAnnontation), but all my elements do not receive any verification on the client side - I check the dom and see that all data-val, data-required attributes, etc. are absent.

I tried different approaches to generating html in my views, but "Prop" and "AnotherProp" are generated using Html.TextBoxFor (m => m.Prop), while my elements are generated in partial - this is where the problems start. If I select Html.TextBoxFor (m => m.Value), all my Element text fields will have the same name / id, so I also tried using Html.TextBox (Model.Id) to generate a unique identifier / name, but still does not have validation properties.

So, there is a way to do my Senario work - I don't mind rewriting it a bit, but I really would like FluentValidation to write my html for me.

My backup solution would be to make my own Html helpers to create the correct Html with attributes, but it suck, I think, since I would have to update these helpers when new releases / fixes were made either by FluentValidation, or jquery validation or link in mvc between them.

+6
asp.net-mvc-3 unobtrusive-validation
source share
1 answer

In partial, before each instance of ElementsVM you must set a unique prefix using ViewData.TemplateInfo.HtmlFieldPrefix, for example:

 var i = 0; foreach (var element in Model) { ViewData.TemplateInfo.HtmlFieldPrefix = "Elements[" + i.ToString() + "]"; @Html.TextBoxFor(m => m.Value) i++; } 

This should give you your unobtrusive validation attributes, and work with the default model binding.

counsellorben

+8
source share

All Articles