ASP.NET MVC HtmlHelper - how do I write an attribute without a value?

混江龙づ霸主 提交于 2019-12-11 04:06:52

问题


I would like to be able to write attributes without values, such as autofocus. Now, I can do this:

@Html.TextBoxFor(m => m.UserName, new { autofocus = true })

But of course this writes:

<input id="UserName" type="text" value="" name="UserName" autofocus="True">

Is there a way to get the attribute written without the value?


回答1:


Commenter alok_dida is correct.

Use:

@Html.TextBoxFor(m => m.UserName, new { autofocus = "" })



回答2:


Here's a simple way to achieve what you want. Note that this could easily be adapted for multiple attributes, variable attributes etc.

public static class HtmlHelperExtensions
{
    private static readonly FieldInfo MvcStringValueField = 
                    typeof (MvcHtmlString).GetField("_value",
                            BindingFlags.Instance | BindingFlags.NonPublic);

    public static MvcHtmlString TextBoxAutoFocusFor<TModel, TProperty>(
                            this HtmlHelper<TModel> htmlHelper, 
                            Expression<Func<TModel, TProperty>> expression, 
                            object htmlAttributes = null)
    {
       if(htmlAttributes == null) htmlAttributes  = new { }

       var inputHtmlString =htmlHelper.TextBoxFor(expression, htmlAttributes);

       string inputHtml = (string) MvcStringValueField.GetValue(inputHtmlString);

       var newInputHtml = inputHtml.TrimEnd('>') + " autofocus >";

       return MvcHtmlString.Create(newInputHtml);
    }
}

Usage example

@Html.TextBoxAutoFocusFor(m => m.UserName)

@Html.TextBoxAutoFocusFor(m => m.UserName, new { data-val-foo="bob"  })

I'm sure someone will mention reflection is slow, which it is, but if the performance of reading that string is something that matters to you. I doubt you'd be using the html helpers to begin with.



来源:https://stackoverflow.com/questions/16023943/asp-net-mvc-htmlhelper-how-do-i-write-an-attribute-without-a-value

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