Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render span tag with title attribute with ASP.NET MVC 3 Helpers

Tags:

It's possible to add a HTML title attribute to an input tag like so:

@Html.TextBoxFor(model => model.Name, new { title = "Customer name" }) 

Is there a similar helper for static text? With @Html.DisplayFor(model => model.Name) I can render the text from a model property. How can I add HTML attributes so that I get a span tag rendered like this:

<span title="Customer name">ABC</span> 
like image 461
Slauma Avatar asked May 14 '11 11:05

Slauma


1 Answers

Custom html helper is probably the neatest solution.

public static MvcHtmlString SpanFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) {     var valueGetter = expression.Compile();     var value = valueGetter(helper.ViewData.Model);      var span = new TagBuilder("span");     span.MergeAttributes(new RouteValueDictionary(htmlAttributes));     if (value != null)     {         span.SetInnerText(value.ToString());     }      return MvcHtmlString.Create(span.ToString()); } 

=>

@Html.SpanFor(model => model.Name, new { title = "Customer name" }) 
like image 91
Necros Avatar answered Oct 12 '22 09:10

Necros