【问题标题】:Get DisplayName Attribute without using LabelFor Helper in asp.net MVC在 asp.net MVC 中不使用 LabelFor Helper 获取 DisplayName 属性
【发布时间】:2011-04-22 14:19:27
【问题描述】:

检索模型中项目的显示名称属性的最佳方法是什么?我看到很多人都在使用 LabelFor 帮助器,但如果我只想列出数据,标签是不合适的。如果我只想打印出来,比如一个段落,有没有一种简单的方法来获取名称属性?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 html-helper


    【解决方案1】:
    <p>
        <%= Html.Encode(
            ModelMetadata.FromLambdaExpression<YourViewModel, string>(
                x => x.SomeProperty, ViewData).DisplayName
        ) %>
    <p>
    

    显然,为了避免意大利面条式代码,编写一个助手总是一个好主意:

    public static class HtmlExtensions
    {
        public static MvcHtmlString GetDisplayName<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression
        )
        {
            var metaData = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
            string value = metaData.DisplayName ?? (metaData.PropertyName ?? ExpressionHelper.GetExpressionText(expression));
            return MvcHtmlString.Create(value);
        }
    }
    

    然后:

    <p>
        <%: Html.GetDisplayName(x => x.SomeProperty) %>
    </p>
    

    【讨论】:

    • 谢谢,这正是我所追求的,还有更多!
    • 请注意,您需要以下usings: using System.Linq;使用 System.Linq.Expressions;
    • 这样做对性能有何影响?我喜欢在所有视图中使用它的想法,但这听起来比在 .cshtml 中包含文本要复杂得多
    • 有谁知道这是在 MVC3 还是 MVC4 beta 中添加的?
    • 在 MVC 4 中称为 DisplayNameFor。
    【解决方案2】:

    你应该尝试新的现有功能:

    <% Html.DisplayNameFor(m => m.YourProperty) %>
    

    【讨论】:

    • 剃刀:@Html.DisplayNameFor(model => model.SomeProperty)
    【解决方案3】:

    在我看来,您应该使用字符串作为结果类型,否则您会跳过编码机制。另一点是,在某些情况下,您需要将 DisplayName 作为字符串(即填充 WebGrid 类中的列)。

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多