asp.net核心Razor Pages:希望DisplayAttribute Description显示为标题/工具提



我有一个asp.net核心(.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://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute.description?view=net-5.0(表示";Description属性通常用作工具提示或描述UI元素";,但对于如何实现这一点却一无所知。

您必须手动完成。例如:

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")'/>

为了使其成为一种适当的扩展方法,有一个轻微的调整如下:

public static class Extensions
{
public static string GetDescription<T>(this T _, string propertyName) where T : class
{
if (string.IsNullOrWhiteSpace(propertyName))
{
throw new ArgumentException($"'{nameof(propertyName)}' cannot be null or whitespace.", nameof(propertyName));
}
MemberInfo memberInfo = typeof(T).GetProperty(propertyName);
if (memberInfo == null)
{
return null;
}
return memberInfo.GetCustomAttribute<DisplayAttribute>()?.GetDescription();
}
}

注意包括";这个T_;部分,通过Duck类型和使用丢弃(即"_"部分(作为实际参数本身未使用(只需要的类型(,使其成为任何类(即模型(类型的扩展方法。

用法很简单:

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

希望这有帮助:(

最新更新