HTML helper - add tooltip to TextBoxFor

徘徊边缘 提交于 2019-12-04 21:03:15

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)}
    })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!