HTML helper - add tooltip to TextBoxFor

独自空忆成欢 提交于 2019-12-10 00:07:05

问题


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)}
    })


来源:https://stackoverflow.com/questions/24024563/html-helper-add-tooltip-to-textboxfor

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