How do I display the DisplayAttribute.Description attribute value?

前端 未结 12 1859
醉梦人生
醉梦人生 2020-11-27 03:26

I have a model class, with a property like this:

[Display(Name = \"Phone\", Description=\"Hello World!\")]
public string Phone1 { get; set; }
12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 04:02

    HANDL's answer, updated for ASP.NET Core 2.0

    using System;
    using System.Linq.Expressions;
    using Microsoft.AspNetCore.Html;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
    
    public static class HtmlExtensions
    {
        public static IHtmlContent DescriptionFor(this IHtmlHelper html, Expression> 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)}");
    
            return new HtmlString(modelExplorer.Metadata.Description);
        }
    }
    

提交回复
热议问题