我想在cshtml中使用Description
属性的属性/字段描述
是否可以像使用DisplayName
一样容易地通过@Html.DisplayNameFor(x => ...)
来做到这一点,或者我必须“提取”它?
public class Test
{
[Description("Test description")]
public bool Name { get; set; }
}
我一直在尝试类似的方法,但是没有成功
var desc = typeof(Test)
.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
或
typeof(Test).Attributes
typeof(Test).GetCustomAttributesData();
答案 0 :(得分:2)
您可以为此简单地编写自定义HtmlHelper:
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);
}
}
答案 1 :(得分:0)
我设法用以下代码做到了:
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);
}