65

What is the best way to retrieve the display name attribute for an item in your model? I see a lot of people using the LabelFor helper for everything, but a label isn't appropriate if I just want to list the data out. Is there an easy way just get the Name Attribute if I just want to print it out in, say a paragraph?

4

3 回答 3

113
<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>
于 2010-10-07T21:04:41.557 回答
74

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

<% Html.DisplayNameFor(m => m.YourProperty) %>
于 2013-07-04T13:24:05.043 回答
1

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

于 2012-06-29T10:16:22.423 回答