I am aware that in a custom display or editor template I can get metadata about the model via ViewData.ModelMetadata, which has properties that indicate whether
Sure. First you'll need your attribute which implements IMetadataAware so that DataAnnotationsModelMetadataProvider knows about it
public class TooltipAttribute : Attribute, IMetadataAware {
public TooltipAttribute(string tooltip) {
this.Tooltip = tooltip;
}
public string Tooltip { get; set; }
public void OnMetadataCreated(ModelMetadata metadata) {
metadata.AdditionalValues["Tooltip"] = this.Tooltip;
}
}
You can then access the attribute by creating a helper method:
public static IHtmlString TooltipFor(
this HtmlHelper html,
Expression> expression) {
var data = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
if (data.AdditionalValues.ContainsKey("Tooltip"))
return new HtmlString((string)data.AdditionalValues["Tooltip"]);
return new HtmlString("");
}