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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
<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>
Method 2
You should try new existing function :
<% Html.DisplayNameFor(m => m.YourProperty) %>
Method 3
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).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0