HTML helper - add tooltip to TextBoxFor

2020-07-31 20:51发布

问题:

I have a model with some properties, and I put annotations on them, specifically the

[Display(Name="MyName", Description="This is a sample description")]

annotation. I have a form where I use the Html.TextBoxFor() helper and I would like to add a bootstrap tooltip to that control. The contents of the tooltip would be the text from the 'Description' annotation. How can this be done? Should I create a custom extension or could I retrieve the description some other way?

Thanks in advance

回答1:

This helper extracts 'Description' property from DisplayAttribute:

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;

public static class DisplayAttributeExtension
{
    public static string GetPropertyDescription<T>(Expression<Func<T>> expression)
    {
        var propertyExpression = (MemberExpression) expression.Body;
        var propertyMember = propertyExpression.Member;
        var displayAttributes = propertyMember.GetCustomAttributes(typeof (DisplayAttribute), true);
        return displayAttributes.Length == 1 ? ((DisplayAttribute) displayAttributes[0]).Description : string.Empty;
    }
}

Usage example:

TestModel.cs:

public class TestModel
{
    [Display(Name = "MyName", Description = "This is a sample description")]
    public string MyName { get; set; }
}

Index.cshtml:

@model Models.TestModel
@section scripts
{
    <script type="text/javascript">
        $('input[type=text][name=MyName]').tooltip({
            placement: "right",
            trigger: "focus"
        });
    </script>
}
@Html.TextBoxFor(m => m.MyName,
    new Dictionary<string, object>
    {
        {"data-toggle", "tooltip"},
        {"title", DisplayAttributeExtension.GetPropertyDescription(() => Model.MyName)}
    })