Create tooltips using Attributes

1

I created a custom attribute, called ToolTip. I would like to add tooltips on every property that has this attribute.

Example:

In my model I have the following property:

[Required, ToolTip("Neste campo você deve inserir um nome.")]
public string Nome { get; set; }

And in the view:

@Html.TextBoxFor(m => m.Nome, new { @class = "form-control" })

Rendering:

<input class="form-control" data-val="true" data-val-required="O campo Nome é obrigatório." id="Nome" name="Nome" type="text" value="">

I'd like you to render with the bootstrap tooltip attributes, like this:

<input data-toggle="tooltip" data-original-title="Neste campo você deve inserir um nome." class="form-control" data-val="true" data-val-required="O campo Nome é obrigatório." id="Nome" name="Nome" type="text" value="">

Any suggestions?

    
asked by anonymous 12.02.2016 / 20:47

2 answers

2

I would say ideally you write your own extension to generate <input> . The original source can help . See this method:

private static MvcHtmlString InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes)
    { ... }

Here you could use:

@Html.TextBoxWthTooltipFor(model => model.Nome, ...)
    
12.02.2016 / 21:03
0

I ended up going the other way. I realized that I could put the tooltip in a span tag instead of putting it in the element itself.

It looks like this:

public static MvcToolTip ToolTipFor<TModel, TValue> (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression,  string placement = "right")
{
    var exp = (MemberExpression) expression.Body;
    var attributes = exp.Expression.Type.GetProperty(exp.Member.Name).GetCustomAttributes(typeof(ToolTipAttribute), false);

    var message = (((ToolTipAttribute) attributes[0]).Description);

    return new MvcToolTip(htmlHelper.ViewContext, message, placement);
}

public class MvcToolTip : IDisposable
{
    private readonly TextWriter _writer;

    public MvcToolTip(ViewContext viewContext, string message, string placement = "right")
    {
        _writer = viewContext.Writer;

        _writer.Write("<span data-toggle='tooltip' data-original-title='" + message + "' data-placement='" + placement + "'>");

    }

    public void Dispose()
    {
        _writer.Write("</span>");
    }
}

Usage:

@using (Html.ToolTipFor(m => m.Pessoa.Nome))
{
    @Html.TextBoxFor(m => m.Pessoa.Nome, new {@class = "form-control"})
}
<script> $("[data-toggle='tooltip']").tooltip(); </script>
    
07.03.2016 / 00:44