How do I display the DisplayAttribute.Description attribute value?

前端 未结 12 1920
醉梦人生
醉梦人生 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

    ...and if you prefer to have the description as a tooltip in the form label, add a Tag Helper like this:

    using System;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using Microsoft.AspNetCore.Razor.TagHelpers;
    
    /// 
    ///  implementation targeting <label> elements with an asp-for attribute.
    /// Adds a title attribute to the <label> with the Description property from the model data annotation DisplayAttribute.
    /// 
    [HtmlTargetElement("label", Attributes = ForAttributeName)]
    public class LabelTitleTagHelper : TagHelper
    {
        private const string ForAttributeName = "asp-for";
    
        /// 
        /// Creates a new .
        /// 
        /// The .
        public LabelTitleTagHelper(IHtmlGenerator generator)
        {
            Generator = generator;
        }
    
        /// 
        public override int Order
        {
            get
            {
                return -1000;
            }
        }
    
        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }
    
        protected IHtmlGenerator Generator { get; }
    
        /// 
        /// An expression to be evaluated against the current model.
        /// 
        [HtmlAttributeName(ForAttributeName)]
        public ModelExpression TitleFor { get; set; }
    
        /// 
        /// Does nothing if  is null.
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
    
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
    
            var metadata = TitleFor.Metadata;
    
            if (metadata == null)
            {
                throw new InvalidOperationException(string.Format("No provided metadata ({0})", ForAttributeName));
            }
    
            if (!string.IsNullOrWhiteSpace(metadata.Description))
                output.Attributes.SetAttribute("title", metadata.Description);
        }
    }
    

    That will create a new title attribute with the Description property from the model's data annotation DisplayAttribute.

    The beautiful part is that you don't need to touch your generated scaffolded views! Because this Tag Helper is targeting the asp-for attribute of the label element that is already there!

提交回复
热议问题