我经常有像这样的C#代码
[DisplayName("Number of Questions")]
public int NumberOfQuestions { get; set; }
我使用DisplayName
属性在显示时添加空格的地方。如果没有明确提供DisplayName
注释,是否有选项可以告诉 MVC 默认添加空格?
有两种方法。
1.覆盖标签用于并创建自定义 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 帮助程序在创建后可以重复使用。
Humanizer 是一个非常受欢迎的库,我用它来做这个。
https://github.com/Humanizr/Humanizer
"PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence"