asp.net MVC扩展了DataAnnotions

lon*_*dsi 4 asp.net-mvc data-annotations

以及DisplayName例如.

[DisplayName("Address line 1 ")]
public string Address1{get; set;}

Html.LabelFor(model => model.Address1) 
Run Code Online (Sandbox Code Playgroud)

我需要显示工具提示,例如.

[DisplayName("Address line 1 ")]
[ToolTip("The first line of your address as it appears on you bank statement")]
public string Address1{get; set;}

Html.LabelFor(model => model.Address1) 
Html.ToolTipFor(model => model.Address1) 
Run Code Online (Sandbox Code Playgroud)

我可以扩展DisplayName DataAnnotation来执行此操作吗?我看不出它是如何完成的.

谢谢!

ale*_*exn 6

我就是这样做的.一些欧洲冠军联赛的时间,如果你愿意,我明天可以澄清代码.

首先是一个属性:

public class TooltipAttribute : DescriptionAttribute
{
    public TooltipAttribute()
        : base("")
    {

    }

    public TooltipAttribute(string description)
        : base(description)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

然后是一个html帮助器,允许我们编写Html.TooltipFor():

public static class HtmlHelpers
{
    public static MvcHtmlString ToolTipFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        var exp = (MemberExpression)expression.Body;
        foreach (Attribute attribute in exp.Expression.Type.GetProperty(ex.Member.Name).GetCustomAttributes(false))
        {
            if (typeof(TooltipAttribute) == attribute.GetType())
            {
                return MvcHtmlString.Create(((TooltipAttribute)attribute).Description);
            }
        }
        return MvcHtmlString.Create("");
    }
}
Run Code Online (Sandbox Code Playgroud)

用法就是:

你的型号:

public class User
{
    [Tooltip("This is the attribute for FirstName")]
    public string FirstName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在你看来:

<%= Html.ToolTipFor(x => x.FirstName) %>
Run Code Online (Sandbox Code Playgroud)