问题
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