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

前端 未结 5 1919
离开以前
离开以前 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<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" })
    
    0 讨论(0)
  • 2021-02-05 07:40

    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>
    
    0 讨论(0)
  • 2021-02-05 07:47

    You use the below

    <span title="Customer name">@Html.DisplayTextFor(m => m.CustomerName)</span>
    
    0 讨论(0)
  • 2021-02-05 07:49
    <span title="Customer name">@Model.Name</span>
    
    0 讨论(0)
  • 2021-02-05 07:50

    Ugly, but works ;-) (required field, without rendering .EditorFor content get lost during submit, even HTML comment around does not work, tested on System.Web.Mvc 5.0.0.0)

    <b style="display:none">@Html.EditorFor(model => model.UserName)</b>
    <input name="UserName" disabled readonly value=@Html.DisplayTextFor(model => model.UserName)>
    

    Original looked like:

    <input class="text-box single-line" data-val="true" data-val-required="The User Name field is required." id="UserName" name="UserName" type="text" value="Hate Razor !">
    
    0 讨论(0)
提交回复
热议问题