Reputation: 2009
I'd want to use in cshtml description of property/field from Description
attribute
Is it possible to do it as easily as with DisplayName
by using @Html.DisplayNameFor(x => ...)
or I have to "extract it"
public class Test
{
[Description("Test description")]
public bool Name { get; set; }
}
I've been trying with something like that, but without any success
var desc = typeof(Test)
.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
or
typeof(Test).Attributes
typeof(Test).GetCustomAttributesData();
Upvotes: 1
Views: 743
Reputation: 2009
I managed to do it with this code:
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)}");
var metadata = (DefaultModelMetadata)modelExplorer?.Metadata;
if (metadata == null)
{
return new HtmlString(string.Empty);
}
var text = (metadata
.Attributes
.Attributes // yes, twice
.FirstOrDefault(x => x.GetType() == typeof(DescriptionAttribute)) as DescriptionAttribute)
?.Description;
var output = HttpUtility.HtmlEncode(text ?? string.Empty);
return new HtmlString(output);
}
Upvotes: 0
Reputation: 2311
You can simply write a custom HtmlHelper for that:
public static class HtmlHelpers
{
public static IHtmlContent DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
DescriptionAttribute descriptionAttribute = null;
if (expression.Body is MemberExpression memberExpression)
{
descriptionAttribute = memberExpression.Member
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.SingleOrDefault();
}
return new HtmlString(descriptionAttribute?.Description ?? string.Empty);
}
}
Upvotes: 2