4

Name attribute works proper, but ShortName doesn't work.

[Display(Name = "Date of the transfer the task", ShortName = "Trans date")]
public DateTime TransferDate { get; set; }

Even when I delete Name attribute, ShortName is ignored ("TransferDate" displays in the column header).

In the view I do this:

@Html.DisplayNameFor(model => model.TransferDate)
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Egor Shoba
  • 95
  • 1
  • 8
  • Check out this answer: [How can I use the ShortName property...](http://stackoverflow.com/questions/14255463/how-can-i-use-the-shortname-property-of-the-display-attribute-for-my-table-heade) – scheien Jun 11 '14 at 05:40
  • 1
    @scheien Does it mean that it's impossible without writing my own helper? I thought it should be automatic too.. – Egor Shoba Jun 11 '14 at 05:44
  • I guess so according to that post. You are also referencing the `DisplayName` attribute in your view => `@Html.DisplayNameFor(...)`. I'm unaware of any fallbacks to ShortName to be honest :-) – scheien Jun 11 '14 at 05:45

1 Answers1

7

If you look at the Description for the ShortName property on the Display Attribute you'll see that it has a pretty limited scope out of the box:

Short Name Description

Of course, that doesn't limit you from leveraging that value on your Model Metadata, but there aren't any native helpers that do so.

Starting with MVC 2, ModelMetadata provides two methods to access the underlying data: FromStringExpression and FromLambdaExpression, so you don't really need to start from scratch in writing your own helper or extension method.

If you hate writing HTML helper methods, you can do this all inline:

@ModelMetadata.FromLambdaExpression<RegisterModel, string>( 
            model => model.TransferDate, ViewData).ShortDisplayName} )  

But it's also perfectly valid to add an extension method for consistency of access, deduplication of code, and improved error handling

public static class MvcHtmlHelpers
{
   public static MvcHtmlString ShortNameFor<TModel, TValue>(this HtmlHelper<TModel> self, 
           Expression<Func<TModel, TValue>> expression)
   {
       var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
       var name = metadata.ShortDisplayName ?? metadata.DisplayName ?? metadata.PropertyName;

       return MvcHtmlString.Create(string.Format(@"<span>{0}</span>", name));
   }
}

And then use like any other helper method:

@Html.ShortNameFor(model => model.TransferDate)

Further Reading:

KyleMit
  • 30,350
  • 66
  • 462
  • 664