HTML帮手 - 添加工具提示TextBoxFor [英] HTML helper - add tooltip to TextBoxFor
问题描述
我有一些特性的模型,我把注释它们,特别是
I have a model with some properties, and I put annotations on them, specifically the
[Display(Name="MyName", Description="This is a sample description")]
注释。我有一个表格,我用Html.TextBoxFor()助手,我想一个引导提示添加到该控件。工具提示的内容是从说明注释的文本。如何才能做到这一点?我应该创建一个自定义扩展或者我可以检索说明一些其他的方式?
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?
在此先感谢
推荐答案
这个帮手提取'说明'从DisplayAttribute属性:
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;
}
}
用法示例:
TestModel.cs:
TestModel.cs:
public class TestModel
{
[Display(Name = "MyName", Description = "This is a sample description")]
public string MyName { get; set; }
}
Index.cshtml:
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)}
})
这篇关于HTML帮手 - 添加工具提示TextBoxFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!