c# – 我可以告诉MVC将pascal-cased属性自动分隔成单词吗?
发布时间:2020-12-15 21:05:53 所属栏目:百科 来源:网络整理
导读:我经常使用C#代码 [DisplayName("Number of Questions")] public int NumberOfQuestions { get; set; } 我在显示时使用DisplayName属性添加空格的位置.如果未明确提供DisplayName注释,是否有一个选项可以告诉MVC默认添加空格? 谢谢 解决方法 有两种方法. 1.
我经常使用C#代码
[DisplayName("Number of Questions")] public int NumberOfQuestions { get; set; } 我在显示时使用DisplayName属性添加空格的位置.如果未明确提供DisplayName注释,是否有一个选项可以告诉MVC默认添加空格? 谢谢 解决方法
有两种方法.
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帮助程序可以在创建后重用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |