Leverage DataAnnotations when building views

Jan 29, 2011 at 11:26 PM

When Scaffolding generates views, it pays no attention to DataAnnotations attributes that are defined in the model. For example, instead of

String.Format("{0:g}", item.Founded)
would be much better to use
Html.DisplayFor(m => item.Founded)

so that, if I have DataType defined as DataType.Date I will get appropriate formatting out of the box.

Similarly, in Index view DisplayName is ignored as well. I don't know whether it makes to scan these values from the source file, or there are some APIs, or even have something like 

@Html.LabelFor(m => Model.First().City)

instead of City - but showing simply the field name is certainly not good enough.

Can't wait for next installment of Steve's blog where he describes how to modify T4 templates!

This was my big grip with generated views in MVC2 (I think MVC2 did the same thing as MVC1, which went live before DataAnnotations). Now is a perfect opportunity for some imporvement.