I have an asp.net core (.Net 5) Razor Pages application. In my model I have a property decorated like so:
[Display(Name = "Borrower Name", Prompt = "Borrower Name", Description = "Restrict the search results by borrower name.")]
[StringLength(255)]
public string BorrowerName { get; set; }
I want the "Description" property set above to render as the input's title (aka tooltip). Here is how I am rendering it. It renders correctly, and the placeholder is correctly set to the Prompt ("Borrower Name"), but my Description does not get rendered to the "title" attribute. What am I missing?
<label asp-for="BorrowerName" class="form-label"></label>
<input asp-for="BorrowerName" class="form-control" />
Here is what gets rendered:
<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="">
The documentation (https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute.description?view=net-5.0) says "The Description property is typically used as a tooltip or description UI element", but not a clue as to how to make that happen.
You have to do it manually. As an example:
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();
}
}
Usage:
<input asp-for="BorrowerName" class="form-control" title='@Extensions.GetDescription<YourClass>("BorrowerName")'/>