首页 > 解决方案 > TagHelper ModelExpression 元数据中不存在描述属性文本

问题描述

尝试编写自定义 TagHelper 来显示Description模型属性的属性。一切似乎都正常工作,但描述文本没有传递到我的 ModelExpression 元数据,它仍然存在null

这是一个 asp.net core 2.1 应用程序。我在我的 TagHelper's 中遇到了一个断点Process,所以它正在运行。DisplayName道具在 中是正确的,For.Metadata因此ModelExpression For正确解析。

模型是在另一个程序集中定义的,而不是使用它的代码,这可能是一个问题吗?

模型:

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

标签助手:

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

用法:

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

使用智能感知,我可以看到For.Metadata.AttributesCollection 包含DescriptionAttribute带有正确文本的 a。我认为Description元数据应该是这个是错误的吗?

标签: c#asp.net-coreasp.net-core-tag-helpers

解决方案


已解决,从github 问题中发现,该问题System.ComponentModel.DescriptionAttribute在 asp.net 核心中不受支持,并且System.ComponentModel.DataAnnotations.DisplayAttribute具有Description将相关元数据文本填充到ModelExpression

这有点难以找到文档,希望有人在谷歌上搜索可以在这里找到帮助。

tl;博士 - 更改[Description("blah")][Display(Description="blah")]


推荐阅读