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

前端 未结 5 1993
离开以前
离开以前 2021-02-05 07:11

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

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


        
5条回答
  •  花落未央
    2021-02-05 07:32

    Custom html helper is probably the neatest solution.

    public static MvcHtmlString SpanFor(this HtmlHelper helper, Expression> 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" })
    

提交回复
热议问题