微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 我可以告诉MVC将pascal-cased属性自动分隔成单词吗?

我经常使用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帮助程序可以在创建后重用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐