Banshee
Banshee

Reputation: 15827

Create a Html.MyControlFor

Hi,

I am implementing a jquery tooltip on my MVC 2 site and to make things easier I have created a customAttribute to decorate the properties with (like Display). My thought is to populate the tooltip with text from this attribute.

What I need now is a Html.ToolTipFor(model => mode.MyProperty) helper. I have started with this :

public static string ToolTipFor(this HtmlHelper htmlHelper, Expression<Func<AdRegister, bool>> action)
        {}

But Im not sure that this is the right way, I do want to use this helper on other pages but the AdRegister.

I have ofcourse done a couple of helpers before but not with a Expression as inparameter.

My thought here is to read the attribute with reflection and by that generate the code for a tooltip.

Pleas help

BestRegards

Upvotes: 0

Views: 211

Answers (1)

Luk&#225;š Novotn&#253;
Luk&#225;š Novotn&#253;

Reputation: 9052

Model:

public class TestModel
{
    [Display(Name = "Mighty title", Description = "Mighty tooltip")]
    public string Title { get; set; }
}

Extension:

public static IHtmlString TooltipFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);

    var span = new TagBuilder("span");
    span.Attributes.Add("title", metadata.Description);
    span.Attributes.Add("class", "tooltip");

    span.SetInnerText(metadata.DisplayName);

    return MvcHtmlString.Create(span.ToString());
}

Usage:

@Html.TooltipFor(m => m.Title)
or
<%: Html.TooltipFor(m => m.Title) %>

Note the use of IHtmlString and TModel and TValue. IHtmlString allows you to write html output without using <%= or @Html.Raw. TModel and TValue allows you to use it on any property on any model.

Upvotes: 1

Related Questions