1

我有一个带有一些属性的模型,我在它们上面添加了注释,特别是

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

注解。我有一个使用 Html.TextBoxFor() 帮助器的表单,我想向该控件添加引导工具提示。工具提示的内容将是“描述”注释中的文本。如何才能做到这一点?我应该创建自定义扩展还是可以通过其他方式检索描述?

提前致谢

4

1 回答 1

4

此助手从 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;
    }
}

使用示例:

测试模型.cs:

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

索引.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)}
    })
于 2014-06-03T22:28:02.303 回答