繁体   English   中英

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

[英]Obtaining [Description]'s attribute value in CSHTML

我想在Description属性中的属性/字段的cshtml描述中使用

是否可以通过使用@Html.DisplayNameFor(x => ...)来像使用DisplayName一样容易地完成此操作,否则我必须“提取它”

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();

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

我设法用下面的代码做到了:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM