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?
Asked
Active
Viewed 2.8k times
3 Answers
113
<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>

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
Thank you, That's exactly what I'm after plus more! – Graham Conzett Oct 08 '10 at 15:24
-
3Note that you need the following `using`s for this: using System.Linq; using System.Linq.Expressions; – James McCormack Nov 04 '10 at 11:31
-
1What are the performance implications of doing this? I like the idea of using this in all the views, but it sounds way more complex than just having the text in the .cshtml – Farinha May 01 '11 at 16:48
-
Does anyone know whether this was added in MVC3 or MVC4 beta? – GraemeMiller Nov 23 '11 at 17:16
-
36It's called DisplayNameFor in MVC 4. – Tristan Warner-Smith Sep 26 '12 at 13:43
-
Yeah MVC 4+ should use this extension method instead: http://stackoverflow.com/a/17471459/383761 – Hugh Jeffner Jan 25 '16 at 15:02
75
You should try new existing function :
<% Html.DisplayNameFor(m => m.YourProperty) %>

Aelios
- 11,849
- 2
- 36
- 54
-
4Razor: @Html.DisplayNameFor(model => model.SomeProperty) – Eskil Mjelva Saatvedt Nov 04 '15 at 07:12
1
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).

Hardy
- 11
- 1