5

我经常有类似的 C# 代码

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

我使用该DisplayName属性在显示时添加空格的位置。DisplayName如果未明确提供注释,是否有一个选项可以告诉 MVC 默认添加空格?

谢谢

4

1 回答 1

0

有两种方法。

1.Override 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;
     }
    }
    
  • 自定义助手:

    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;
    
      }
    }
    
  • 在 CSHTML 中使用:

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

    您的标签将显示为“您的物业名称”

2.使用资源文件:

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

我会更喜欢第一个解决方案。因为资源文件打算在项目中发挥单独和保留的作用。此外,自定义 HTML 帮助程序一旦创建就可以重复使用。

于 2018-02-27T10:22:44.350 回答