首页 > 解决方案 > 获取CSHTML中[Description]的属性值

问题描述

我想在属性/字段的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();

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

解决方案


您可以简单地为此编写一个自定义 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);
    }
}

推荐阅读