I am building a custom HTML.LabelFor helper that looks like this :
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression, Boolean showToolTip)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
...
}
To be able to get the proper name for the property I am using the following code :
metadata.DisplayName
And on the property of the ModelView class I got :
[DisplayName("Titel")]
The problem is that I also need a description. There is an Attribute called Display and that has Name and Description but I do not see how to extract this with the metadata variable in the above code?
Disclaimer: The following works only with ASP.NET MVC 3 (see the update at the bottom if you are using previous versions)
Assuming the following model:
And the following view:
Inside your custom helper you could fetch this information from the metadata:
Remark: Having
[DisplayName("foo")]and[Display(Name = "bar")]on the same model property is redundant and the name used in the[Display]attribute has precedence inmetadata.DisplayName.UPDATE:
My previous answer won’t work with ASP.NET MVC 2.0. There are a couples of properties that it is not possible to fill by default with
DataAnnotationsin .NET 3.5, andDescriptionis one of them. To achieve this in ASP.NET MVC 2.0 you could use a custom model metadata provider:which you would register in
Application_Start:and then the helper should work as expected: