Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save frankgeerlings/6916576 to your computer and use it in GitHub Desktop.
Save frankgeerlings/6916576 to your computer and use it in GitHub Desktop.
Create useful names for fields instead of the camel cased property names. This one is slightly different in that it also capitalizes just the first word, which for some languages is more appropriate than having all the words' first letters as caps. Inspired largely by http://blog.dotsmart.net/2011/03/28/generating-better-default-displaynames-fro…
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.Mvc;
/// <summary>
/// Model metadata property names are typically CamelCased. When used as a human-readable text, eg. in LabelFor etc, this metadata provider
/// will un-camelcase the name of the property, so you don't have to add a DisplayNameAttribute to every single property in your model.
/// </summary>
/// <remarks>
/// <para>
/// Hook the provider up in Application_Start by assigning an instance of it to ModelMetadataProviders.Current, or (if you use a dependency injection
/// framework) bind System.Web.Mvc.ModelMetadataProvider to this class.
/// </para>
/// <para>
/// Inspired by: http://blog.dotsmart.net/2011/03/28/generating-better-default-displaynames-from-models-in-asp-net-mvc-using-modelmetadataprovider/
/// </para>
/// </remarks>
public class CamelCaseDisplayNamesModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
private readonly Regex camelCaseRegex = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
/// <summary>
/// Creates a nice DisplayName from the model’s property name if one hasn't been specified
/// </summary>
protected override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor)
{
var metadata = base.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);
if (metadata.DisplayName == null)
{
metadata.DisplayName = this.DisplayNameFromCamelCase(metadata.GetDisplayName());
}
return metadata;
}
private static IEnumerable<string> LowercaseAllButFirst(IEnumerable<string> words)
{
var first = true;
foreach (var word in words)
{
if (first)
{
first = false;
yield return word;
}
else
{
yield return word.ToLower();
}
}
}
private string DisplayNameFromCamelCase(string name)
{
name = string.Join(" ", LowercaseAllButFirst(this.camelCaseRegex.Split(name)));
if (name.EndsWith(" id"))
{
name = name.Substring(0, name.Length - 3);
}
return name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment