user49438
user49438

Reputation: 909

Can I tell MVC to separate pascal-cased properties in to words automatically?

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?

Upvotes: 6

Views: 354

Answers (2)

zeroef
zeroef

Reputation: 1969

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"

Upvotes: 0

Anadi
Anadi

Reputation: 754

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.

Upvotes: 0

Related Questions