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

为君一笑 提交于 2019-12-04 08:59:01

问题


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>

回答1:


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



回答2:


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



回答3:


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>



回答4:


You use the below

<span title="Customer name">@Html.DisplayTextFor(m => m.CustomerName)</span>


来源:https://stackoverflow.com/questions/6001411/render-span-tag-with-title-attribute-with-asp-net-mvc-3-helpers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!