我可以告诉 MVC 将 pascal-cased 属性自动分离为单词吗?

use*_*438 5 c# asp.net-mvc asp.net-mvc-5 displayname-attribute

我经常有 C# 代码,比如

    [DisplayName("Number of Questions")]
    public int NumberOfQuestions { get; set; }
Run Code Online (Sandbox Code Playgroud)

我在哪里使用该DisplayName属性在显示时添加空格。如果DisplayName未明确提供注释,是否可以选择告诉 MVC 默认添加空格?

谢谢

Ana*_*adi 0

有两种方法。

1.重写LabelFor并创建自定义 HTML 帮助器:

  • 自定义 HTML 帮助器的实用程序类:

    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;
     }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 自定义助手:

    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;
    
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 在 CSHTML 中使用:

    @Html.LabelForCamelCase(m=>m.YourPropertyName, new { style="color:red"})
    
    Run Code Online (Sandbox Code Playgroud)

    您的标签将显示为“您的房产名称”

2.使用资源文件:

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

我更喜欢第一个解决方案。因为资源文件的目的是在项目中起到独立和保留的作用。此外,自定义 HTML 帮助程序在创建后可以重复使用。