I have a model class, with a property like this:
[Display(Name = \"Phone\", Description=\"Hello World!\")]
public string Phone1 { get; set; }
...and if you prefer to have the description as a tooltip in the form label, add a Tag Helper like this:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
///
/// implementation targeting <label> elements with an asp-for attribute.
/// Adds a title attribute to the <label> with the Description property from the model data annotation DisplayAttribute.
///
[HtmlTargetElement("label", Attributes = ForAttributeName)]
public class LabelTitleTagHelper : TagHelper
{
private const string ForAttributeName = "asp-for";
///
/// Creates a new .
///
/// The .
public LabelTitleTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
///
public override int Order
{
get
{
return -1000;
}
}
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
protected IHtmlGenerator Generator { get; }
///
/// An expression to be evaluated against the current model.
///
[HtmlAttributeName(ForAttributeName)]
public ModelExpression TitleFor { get; set; }
///
/// Does nothing if is null .
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
var metadata = TitleFor.Metadata;
if (metadata == null)
{
throw new InvalidOperationException(string.Format("No provided metadata ({0})", ForAttributeName));
}
if (!string.IsNullOrWhiteSpace(metadata.Description))
output.Attributes.SetAttribute("title", metadata.Description);
}
}
That will create a new title attribute with the Description property from the model's data annotation DisplayAttribute.
The beautiful part is that you don't need to touch your generated scaffolded views! Because this Tag Helper is targeting the asp-for attribute of the label element that is already there!