This is not so simple since the DataAnnotationsModelMetadataProvider
(what a name!) does not use the Description attribute.
Therefore, to use the Description attribute you will need to do the following:
- Create a custom
ModelMetaDataProvider
.
- Register it as the application's metadata provider.
- Implement the
DescriptionFor
method.
So...
Here is the custom ModelMetaDataProvider
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
namespace MvcApplication2
{
public class DescriptionModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
ModelMetadata result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
DescriptionAttribute descriptionAttribute = attributes.OfType<DescriptionAttribute>().FirstOrDefault();
if (descriptionAttribute != null)
result.Description = descriptionAttribute.Description;
return result;
}
}
}
Now, registering it is done in the Global.asax file within the Application_Start method as follows:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
// This is the important line:
ModelMetadataProviders.Current = new DescriptionModelMetaDataProvider();
}
And eventually, the implementation of the DescriptionFor
method:
using System.Linq.Expressions;
namespace System.Web.Mvc.Html
{
public static class Helper
{
public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string fieldName = ExpressionHelper.GetExpressionText(expression);
return MvcHtmlString.Create(String.Format("<label for=\"{0}\">{1}</label>",
html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName),
metadata.Description));// Here goes the description
}
}
}
This should work, I checked it on my machine.
Shay.