在CSHTML中获取[说明]的属性值

时间:2019-03-27 08:40:54

标签: c# asp.net-core asp.net-core-mvc

我想在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();

2 个答案:

答案 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);
}