Get DisplayName Attribute without using LabelFor Helper in asp.net MVC

asp.netasp.net Mvcasp.net Mvc-3asp.net Mvc-2Html Helper

asp.net Problem Overview


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?

asp.net Solutions


Solution 1 - asp.net

<p>
    <%= Html.Encode(
        ModelMetadata.FromLambdaExpression<YourViewModel, string>(
            x => x.SomeProperty, ViewData).DisplayName
    ) %>
<p>

Obviously in order to avoid the spaghetti code it is always a good idea to write a helper:

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);
    }
}

And then:

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

Solution 2 - asp.net

You should try new existing function :

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

Solution 3 - asp.net

In my opinion you should use a string as a result type because otherwise you skip the encoding mechanism. Another point is that you need the DisplayName in some cases as a string (i.e. populate the columns in a WebGrid class).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGraham ConzettView Question on Stackoverflow
Solution 1 - asp.netDarin DimitrovView Answer on Stackoverflow
Solution 2 - asp.netAeliosView Answer on Stackoverflow
Solution 3 - asp.netHardyView Answer on Stackoverflow