Search code examples
c#asp.net-coreasp.net-core-tag-helpers

Description attribute text not present in TagHelper ModelExpression Metadata


Trying to write a custom TagHelper to display the Description attribute of a model property. Everything seems to work otherwise, but the description text is not passed on to my ModelExpression Metadata, it remains null.

This is an asp.net core 2.1 app. I'm hitting a breakpoint in my TagHelper's Process, so it is being run. The DisplayName prop is correct in For.Metadata, so the ModelExpression For resolves correctly.

The Model is defined in another assembly than the code using it, can this be an issue?

Model:

public class MyModel {
  [Description("a description")]
  [DisplayName("display name")]
  public string MyProperty {get; set;}
}

TagHelper:

[HtmlTargetElement("span", Attributes = AttributeName)]
    public class DescriptionTagHelper : TagHelper
    {
        private const string AttributeName = "asp-description-for";

        /// <summary>
        /// An expression to be evaluated against the current model.
        /// </summary>
        [HtmlAttributeName(AttributeName)]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (!output.IsContentModified)
            {
                output.Attributes.SetAttribute("class", "text-muted");
                output.Content.SetContent(For.Metadata.Description);
            }
        }
    }

Usage:

<span asp-description-for="MyModel.MyProperty"></span>

Using intellisense, i can see that the For.Metadata.Attributes Collection contains a DescriptionAttribute with the correct text. Am i wrong to assume that the Description metadata should be this one?


Solution

  • Solved, found out from a github issue that System.ComponentModel.DescriptionAttribute is not supported in asp.net core, and System.ComponentModel.DataAnnotations.DisplayAttribute has a Description attribute that populates the relevant metadata text in a ModelExpression

    This was sort of hard to find documentation about, hopefully someone googling around finds help here.

    tl;dr - change [Description("blah")] to [Display(Description="blah")]