How do I display the DisplayAttribute.Description attribute value?
Using the technique from this article about how to Display visual hints for the fields in your form, you can access the value via the following:
@Html.TextBoxFor(
model => model.Email ,
new { title = ModelMetadata.FromLambdaExpression<RegisterModel , string>(
model => model.Email , ViewData ).Description } )
I was about to use the accepted answer, but it didn't work for ASP.NET Core 1/2 (a.k.a. MVC 6) because ModelMetadata.FromLambdaExpression
no longer exists and has been moved to ExpressionMetadataProvider
(also usage has been changed slightly).
This is an updated extension method you can use with ASP.NET Core 1.1 & 2:
using System;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
public static class HtmlExtensions
{
public static IHtmlContent DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
if (html == null) throw new ArgumentNullException(nameof(html));
if (expression == null) throw new ArgumentNullException(nameof(expression));
var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, html.ViewData, html.MetadataProvider);
if (modelExplorer == null) throw new InvalidOperationException($"Failed to get model explorer for {ExpressionHelper.GetExpressionText(expression)}");
return new HtmlString(modelExplorer.Metadata.Description);
}
}
ASP.NET Core 1
For ASP.NET Core 1, the same code works, but you'll need different namespace usings
:
using System;
using System.Linq.Expressions;
using Microsoft.AspNet.Html.Abstractions;
using Microsoft.AspNet.Mvc.ViewFeatures;
Usage
@Html.DescriptionFor(model => model.Phone1)
I ended up with a helper like this:
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
public static class MvcHtmlHelpers
{
public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
var description = metadata.Description;
return MvcHtmlString.Create(string.Format(@"<span>{0}</span>", description));
}
}
Thanks to those who led me in the right direction. :)