Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net MVC extending DataAnnotions

As well as DisplayName eg.

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

Html.LabelFor(model => model.Address1) 

I have a requirement to show tooltips eg.

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

Can I extend the DisplayName DataAnnotation to do this? I can't see how it can be done.

Thanks!

like image 276
longhairedsi Avatar asked Feb 27 '23 06:02

longhairedsi


2 Answers

This is how I would do it. Time for some Champions League, I can clarify the code tomorrow if you want.

First a attribute:

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

    }

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

    }
}

And then a html helper to allow us to write 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("");
    }
}

Usage would then be this:

Your model:

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

And in your view:

<%= Html.ToolTipFor(x => x.FirstName) %>
like image 107
alexn Avatar answered Mar 11 '23 22:03

alexn


This should get you in the right direction. It's an extension method that grabs the model property you're passing in. (if you're using MVC3 you can replace MvcHtmlString.Create with new HtmlString()

Html.ToolTipFor(m => m.Address1)

public static IHtmlString ToolTipFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
    MemberExpression ex = (MemberExpression)expression.Body;
    foreach(Attribute attribute in ex.Expression.Type.GetProperty(ex.Member.Name).GetCustomAttributes(true)) {
        if (typeof(TooltipAttribute) == attribute.GetType()) {
            return MvcHtmlString.Create(((TooltipAttribute)attribute).YourTooltipProperty);
        }
    }
    return MvcHtmlString.Create("");

}
like image 39
Buildstarted Avatar answered Mar 11 '23 22:03

Buildstarted