Tom*_*gan 3 data-annotations asp.net-core razor-pages
我有一个 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; }
Run Code Online (Sandbox Code Playgroud)
我希望上面设置的“描述”属性呈现为输入的标题(也称为工具提示)。这是我渲染它的方式。它正确呈现,并且占位符已正确设置为提示(“借款人姓名”),但我的描述未呈现为“标题”属性。我缺少什么?
<label asp-for="BorrowerName" class="form-label"></label>
<input asp-for="BorrowerName" class="form-control" />
Run Code Online (Sandbox Code Playgroud)
这是渲染的内容:
<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="">
Run Code Online (Sandbox Code Playgroud)
文档(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();
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
<input asp-for="BorrowerName" class="form-control" title='@Extensions.GetDescription<YourClass>("BorrowerName")'/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1463 次 |
| 最近记录: |