Skip to content Skip to sidebar Skip to footer

Asp.net Mvc Htmlhelper - How Do I Write An Attribute Without A Value?

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 thi

Solution 1:

Commenter alok_dida is correct.

Use:

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

Solution 2:

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

publicstaticclassHtmlHelperExtensions
{
    privatestaticreadonly FieldInfo MvcStringValueField = 
                    typeof (MvcHtmlString).GetField("_value",
                            BindingFlags.Instance | BindingFlags.NonPublic);

    publicstatic 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.

Post a Comment for "Asp.net Mvc Htmlhelper - How Do I Write An Attribute Without A Value?"