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

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


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" })


<span title="Customer name">@Model.Name</span>


If you are using @HTML.DisplayFor(model=>model.CustomerName) It will render as text, It will not shows any tag inside the values.

If you want to bind the "DisplayFor" using span , Use the below tag,

<span id="CustomerName">@Html.DisplayFor(model=>model.CustomerName)</span>