Dynamic Data Annotations

If you've played around with Dynamic Data or even just watched some of the available screen casts, you're aware that you can annotate your object model fields with various attributes such as

  • Required
  • Range
  • StringLength
  • UIHint
  • DisplayFormat
  • ...

Although these attributes were introduced for use with Dynamic Data, they actually reside in the System. ComponentModel.DataAnnotations namespace - a not-so-subtle hint that they'll probably appear in other non-Dynamic Data contexts as well.

What I quickly (and incorrectly) thought to be missing was a way to simply provide a friendly name for each of my columns in the GridView and DetailsView controls that Dynamic Data builds for me - you know, something like "First Name" for the "fname" column. 

Since the default header text is taken from the data model (the property names from my LINQ to SQL classes, in my case), I could get to "FirstName", but got stuck there.

As it turns out, Dynamic Data also 'reuses' several of the attributes from System.ComponentModel, namely

  • DisplayName
  • Description
  • DefaultValue

So, by decorating an associated meta data class, I was quickly back in business!

 [MetadataType(typeof(EmployeeMetaData))]
partial class Employee
{
}

public class EmployeeMetaData
{
    [DisplayName("First Name")]
    [Description("Please enter the employee's first name")]
    public object Fname{get; set;}
}

image
Now I get a meaningful column name for my end-user along with a tooltip, and by virtue of Dynamic Data, this will come along for the ride everywhere I use the Employee.Fname column!