Jul 5 2011

Building Nice Display Names From Pascal-Case View Model Names in ASP.NET MVC 3

Category: ASP.NET | MVC | Fail TrackerMatt @ 12:56

One of my goals with Fail Tracker is to push the “Convention over Configuration” idea as far as you possibly can within the confines of ASP.NET MVC.  I’m obviously biased, but so far I think I’ve been quite successful, and Fail Tracker is probably the most enjoyable codebase I’ve ever worked with.  One convention I recently implemented eliminates the need to decorate view model properties with the DisplayNameAttribute.  The convention says “Pascal cased property names will be intelligently split into strings with spaces.”  Thanks to the infrastructure and pluggable model metadata system that Fail Tracker uses, implementing this convention was quite easy.

By default in ASP.NET MVC 3, a view model like the following:

public class LogOnForm
{
    [Required]
    [EmailAddress]
    public string EmailAddress { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

will generate a field label that looks like this:

image

Note the missing space between “Email” and “Address.”  This is obviously not what we want.  The way I solved it originally was to apply the DisplayNameAttribute to my view model:

public class LogOnForm
{
    [Required]
    [EmailAddress]
    [DisplayName("Email Address")]
    public string EmailAddress { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

which gives the desired UI:

image

But this seemed pointless to me.  Why should I have to remember to de-Pascal case my property names every time I created a view model?  Fortunately, I don’t have to.  Here’s the “model metadata filter” (a feature of the Fail Tracker application framework) that achieves the same thing:

public class PascalCaseToDisplayNameFilter : IModelMetadataFilter
{
    public void TransformMetadata(System.Web.Mvc.ModelMetadata metadata, IEnumerable<Attribute> attributes)
    {
        if (!string.IsNullOrEmpty(metadata.PropertyName) && !attributes.OfType<DisplayNameAttribute>().Any())
        {
            metadata.DisplayName = metadata.PropertyName.ToStringWithSpaces();
        }
    }
}

The ToStringWithSpaces extension method is a beautiful piece of Regex that James Kolpack gets credit for:

public static class StringExtensions
{
     public static string ToStringWithSpaces(this string input)
     {
         return Regex.Replace(
            input,
            "(?<!^)" + // don't match on the first character - never want to place a space here
            "(" +
            "  [A-Z][a-z] |" + // put a space before "Aaaa"
            "  (?<=[a-z])[A-Z] |" + // put a space into "aAAA" before the first capital
            "  (?<![A-Z])[A-Z]$" + // if the last letter is capital, prefix it with a space too
            ")",
            " $1",
            RegexOptions.IgnorePatternWhitespace);
     }
}

And that’s all there is to it.  Thanks to the application framework that is baked into Fail Tracker, simply creating the PascalCaseToDisplayNameFilter is all that’s necessary.  I can now remove most of my DisplayNameAttributes from my view models.  Do note though that the convention is quite easy to override.  If I do need to alter the labeling for a property, I can still use the DisplayNameAttribute exactly as before.  All my convention does is provide a more reasonable default without getting in the way of doing something different, which is exactly what a good convention should do.

If you want to know more about how these sorts of conventions are automagically wired up in Fail Tracker, feel free to check out Fail Tracker code.  I do plan to write much more about the application framework itself, but it may be a while as I’m targeting a magazine publication for that. Smile

Tags:

blog comments powered by Disqus