Creating tooltips using data annotations in ASP.NET MVC

Posted by ben 18. April 2011 09:20

Here’s a really simple way of creating tooltips on form elements using data annotations on your view model class.

As you may already know, you can control the label text for a view model property by adding a DisplayAttribute and setting it’s Name property:

	[Display(Name = "Product Name:")]
	public string Name { get; set; }

Another property of the DisplayAttribute, is the Description property. However, setting this has no effect on the label generated when using the default LabelFor html helper.

So let’s create our own html helper that sets the “title” attribute of a label, based on the DisplayAttribute’s description property:

	public static MvcHtmlString LabelWithTooltip<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
	{
		var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

		string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
		string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
		
		if (String.IsNullOrEmpty(labelText))
			return MvcHtmlString.Empty;

		var label = new TagBuilder("label");
		label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

		if (!string.IsNullOrEmpty(metaData.Description))
			label.Attributes.Add("title", metaData.Description);
		
		label.SetInnerText(labelText);
		return MvcHtmlString.Create(label.ToString());            
	}

Then we update our view model class to include a description:

	[Display(Name = "Product Name:", Description="The name of the product")]
	public string Name { get; set; }

Now its just a case of swapping out our existing LabelFor tooltip with LabelWithTooltip. If we load our page we see the following:

image

Of course this can easily be jazzed up with one of the many javascript tooltip plugins available.

For example, to use the jQuery TOOLS Tooltip plugin just add a script reference to http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js and add the following to your page (making sure you have referenced jQuery):

<script type="text/javascript">
    $(function () {
        $("label[title]").tooltip({
            // options go here
        });
    });
</script>

When we reload our page and hover over the labels we now get a sexy tooltip:

image

(note that you will need to download the images from the jQuery tools web site).

If you don’t want to use one of the existing attributes to pass your meta data you have two choices.

1) Use the AdditionalMetaDataAttribute which allows you to pass custom key value pairs that you can retrieve from the ModelMetaData.AdditionalValues property.

2) Create a custom attribute e.g. ToolTip attribute. You can then create your own MetaDataProvider that takes the values from your custom attribute and manipulates the underlying ModelMetaData object. There is a great article on doing just that here.

Tags:
Categories C# | ASP.NET | Development

blog comments powered by Disqus