【问题标题】:asp.net core Razor Pages: want DisplayAttribute Description to display as title/tooltipasp.net core Razor Pages:希望 DisplayAttribute 描述显示为标题/工具提示
【发布时间】:2021-06-30 23:10:59
【问题描述】:

我有一个 asp.net core (.Net 5) Razor Pages 应用程序。在我的模型中,我有一个这样装饰的属性:

    [Display(Name = "Borrower Name", Prompt = "Borrower Name", Description = "Restrict the search results by borrower name.")]
    [StringLength(255)]
    public string BorrowerName { get; set; }

我希望上面设置的“描述”属性呈现为输入的标题(又名工具提示)。这是我渲染它的方式。它正确呈现,并且占位符正确设置为提示(“借款人名称”),但我的描述没有呈现为“标题”属性。我错过了什么?

<label asp-for="BorrowerName" class="form-label"></label>
<input asp-for="BorrowerName" class="form-control" />

这是渲染的内容:

<input class="form-control" type="text" data-val="true" data-val-length="The field Borrower Name must be a string with a maximum length of 255." data-val-length-max="255" id="BorrowerName" maxlength="255" name="BorrowerName" placeholder="Borrower Name" value="">

文档 (https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute.description?view=net-5.0) 说“Description 属性通常用作工具提示或描述 UI 元素”,但没有说明如何实现这一点。

【问题讨论】:

    标签: asp.net-core data-annotations razor-pages


    【解决方案1】:

    您必须手动完成。举个例子:

    public static class Extensions
    {
        public static string GetDescription<T>(string propertyName) where T: class
        {
            MemberInfo memberInfo = typeof(T).GetProperty(propertyName);
            if (memberInfo == null)
            {
                return null;
            }
    
            return memberInfo.GetCustomAttribute<DisplayAttribute>()?.GetDescription();
        }
    }
    

    用法:

    <input asp-for="BorrowerName" class="form-control" title='@Extensions.GetDescription<YourClass>("BorrowerName")'/>
    

    【讨论】:

    • 对渲染标题的轻微修正:title='(@Extensions.GetDescription("BorrowerName"))'
    猜你喜欢
    • 2013-02-21
    • 2021-07-08
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多