在ASP.NET MVC中,如何在CamelCase上将属性名称显示为标签拆分

And*_*mer 11 asp.net-mvc-2

我知道我以前见过这个.我不记得它是C4MVC模板演示还是输入构建器的东西!我需要知道如何使用CamelCasing我的视图模型属性的约定,并在标签中将"CamelCasedProperty"呈现为"Camel Cased Property".这应该由创建新视图向导处理,而不是以编程方式处理它.

Kel*_*sey 20

我认为你想要的东西在vanilla ASP.NET MVC 2中是不可能的.

在ASP.NET MVC 2中,您需要使用带有所需文本的DisplayName属性来装饰模型,然后自动生成的向导将用于LabelFor输出属性的标签.例如:

class MyModel()
{
    [DisplayName("Your Property Name")]
    public string YourPropertyName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后在视图中:

<%= Html.LabelFor(m => m.YourPropertyName) %>
Run Code Online (Sandbox Code Playgroud)

如果你看到它的演示正在做一些其他的方式也有可能是从MvcContrib项目InputBuilders.

这是我认为你所指的项目部分的直接链接:

http://www.lostechies.com/blogs/hex/archive/2009/06/09/opinionated-input-builders-for-asp-net-mvc-part-2-html-layout-for-the-label. ASPX

以红色突出显示的文本是来自"模型"类型的标签.标签是从PropertyInfo对象创建的,该对象表示模式的相应属性.

标签是Property Name.

标签是在pascal case属性名称上拆分的Property Name.

使用应用于属性的标签属性指定标签.


And*_*mer 7

经过一番探索之后,我发现了一些我感兴趣的事情.看这个C4MVC视频.我确信这可能已经在MVC Contrib中作为输入构建器完成了.但是,我非常有兴趣了解所有不足之处,以便我可以为即将出版的书"ASP.NET MVC Cookbook"(无耻的插件供公众评审)学习.这是我提出的解决方案,只需要我在生成的代码中将Html.LabelFor重命名为Html.LabelFor2形成"创建新视图":

我创建了一个方法来从传入的lambda中获取属性名称.然后我创建了另一个方法来解析名称中包含的大写字母的属性名称.

using System;
using System.Linq.Expressions;
using System.Text.RegularExpressions;

namespace FuryPartners.WebClient.Helpers
{
    public class HelperUtilities
    {
        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 "oops";
            }
        }

        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)

然后,我将HtmlHelper扩展为具有LabelFor2方法,该方法构建并传递属性名称的适当显示格式.

using System;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace FuryPartners.WebClient.Helpers
{
    public static class LabelHelpers
    {
        public static MvcHtmlString LabelFor2<T, TResult>(this HtmlHelper<T> helper, Expression<Func<T, TResult>> expression)
        {
            string propertyName = HelperUtilities.PropertyName(expression);
            string labelValue = HelperUtilities.SplitCamelCase(propertyName);

            string label = String.Format("<label for=\"{0}\">{1}</label>", propertyName, labelValue);
            return MvcHtmlString.Create(label);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)