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.