6

I often have C# code like

    [DisplayName("Number of Questions")]
    public int NumberOfQuestions { get; set; }

Where I use the DisplayName property to add in spaces when it is displayed. Is there an option to tell MVC to add spaces by default if the DisplayName annotation is not explicitly provided?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
user49438
  • 889
  • 7
  • 20
  • 1
    According to this answer, you can only apply constants, http://stackoverflow.com/questions/11654740/is-it-possible-to-use-a-variable-for-the-displayname-something-data-anno – nixkuroi Apr 14 '17 at 17:58
  • 2
    you could probably have your own custom `DisplayFor`, where you grabbed the property name and manipulated it. But I'd opt for just hardcoding it. – Jonesopolis Apr 14 '17 at 17:59
  • Use reflection to get property name from class definition, then create a custom `Html.DisplayFor` or using `DisplayTemplate` containing regex which inserting whitespaces between end of previous word (if exists) and capital letters. – Tetsuya Yamamoto Apr 17 '17 at 09:24

2 Answers2

0

There are two ways.

1.Override LabelFor and creating a custom HTML helper:

  • Utility class for Custom HTML helper:

    public class CustomHTMLHelperUtilities
    {
    // Method to Get the Property Name
    internal static string PropertyName<T, TResult>(Expression<Func<T, TResult>> expression)
     {
        switch (expression.Body.NodeType)
        {
            case ExpressionType.MemberAccess:
                var memberExpression = expression.Body as MemberExpression;
                return memberExpression.Member.Name;
            default:
                return string.Empty;
        }
     }
     // Method to split the camel case
     internal static string SplitCamelCase(string camelCaseString)
     {
        string output = System.Text.RegularExpressions.Regex.Replace(
            camelCaseString,
            "([A-Z])",
            " $1",
            RegexOptions.Compiled).Trim();
        return output;
     }
    }
    
  • Custom Helper:

    public static class LabelHelpers
    {
     public static MvcHtmlString LabelForCamelCase<T, TResult>(this HtmlHelper<T> helper, Expression<Func<T, TResult>> expression, object htmlAttributes = null)
      {
        string propertyName = CustomHTMLHelperUtilities.PropertyName(expression);
        string labelValue = CustomHTMLHelperUtilities.SplitCamelCase(propertyName);
    
        #region Html attributes creation
        var builder = new TagBuilder("label ");
        builder.Attributes.Add("text", labelValue);
        builder.Attributes.Add("for", propertyName);
        #endregion
    
        #region additional html attributes
        if (htmlAttributes != null)
        {
            var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            builder.MergeAttributes(attributes);
        }
        #endregion
    
        MvcHtmlString retHtml = new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
        return retHtml;
    
      }
    }
    
  • Use in CSHTML:

    @Html.LabelForCamelCase(m=>m.YourPropertyName, new { style="color:red"})
    

    Your label will display as 'Your Property Name'

2.Using Resource File:

[Display(Name = "PropertyKeyAsperResourceFile", ResourceType = typeof(ResourceFileName))]
public string myProperty { get; set; }

I will prefer the first solution. Because a resource file is intend to do a separate and reserved role in a project. Additionally the custom HTML helper can be reused once created.

Anadi
  • 744
  • 9
  • 24
0

Humanizer is a very popular library that I've used for this.

https://github.com/Humanizr/Humanizer

"PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence"
zeroef
  • 1,949
  • 23
  • 32