c# - 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.Attributes
Collection 包含DescriptionAttribute
带有正确文本的 a。我认为Description
元数据应该是这个是错误的吗?
解决方案
已解决,从github 问题中发现,该问题System.ComponentModel.DescriptionAttribute
在 asp.net 核心中不受支持,并且System.ComponentModel.DataAnnotations.DisplayAttribute
具有Description
将相关元数据文本填充到ModelExpression
这有点难以找到文档,希望有人在谷歌上搜索可以在这里找到帮助。
tl;博士 - 更改[Description("blah")]
为[Display(Description="blah")]
推荐阅读
- c# - EF Core:INSERT 语句与 FOREIGN KEY 约束冲突
- css - 如何启用字体变体,如“斜体显示”
- javascript - Cookie 信息弹出制造商 - 在用户拒绝后如何不发送 cookie?
- angular - Angular - Jasmine 单元测试的模拟 Promise 方法
- ruby-on-rails - 检测并删除上传的 ZIP 文件中的所有可执行文件
- google-app-engine - 为自定义域启用 SSL 时未在 Google App Engine 中列出子域
- android - getAppStandbyBucket 需要未知权限
- php - htaccess 404 重定向适用于除 .php 之外的每个扩展名或路径
- angular - 如何在 ngFor 中使用响应式表单
- c# - Enum.GetValues() 是否使用反射?