1

I have a model and a field... etc. this is trivial. But, I need get from my view the "Description" attribute from a field and your "Name" atrribute. With @Html... is possible the return of this with "DisplayNameFor", obvious. But, how to get the "Description" attribute? Not have a Helper like @Html.DisplayDescription? Is possible get this?

[Column("abc")]
[Display(Description = "The Description", GroupName = "The Group", Name = "The Name")]
public string field { get; set; }

Thank you for help. Sorry the not good english. ;)

GustavoAdolfo
  • 361
  • 1
  • 9
  • 23

1 Answers1

16

You could get it from the metadata:

@model MyViewModel

@{
    var description = ModelMetadata.FromLambdaExpression<MyViewModel, string>(x => x.field, ViewData).Description;
}

@description

Or if you are as me finding this absolutely horrible code to be written in a view you could encapsulate it in a reusable helper:

public static class HtmlExtensions
{
    public static IHtmlString DescriptionFor<TModel, TValue>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TValue>> expression
    )
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        var description = metadata.Description;
        return new HtmlString(description);
    }
}

so that in your view you could use like that:

@model MyViewModel

@Html.DescriptionFor(x => x.field)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928