2

我希望能够编写没有值的属性,例如autofocus. 现在,我可以这样做:

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

但是,这当然写道:

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

有没有办法让没有值的属性写入?

4

2 回答 2

1

评论者 alok_dida 是正确的。

利用:

@Html.TextBoxFor(m => m.UserName, new { autofocus = "" })
于 2014-03-23T23:35:29.300 回答
0

这是实现您想要的目标的简单方法。请注意,这可以很容易地适用于多个属性、变量属性等。

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);
    }
}

使用示例

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

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

我敢肯定有人会提到反射很慢,确实如此,但是如果读取该字符串的性能对您很重要。我怀疑你会使用 html 助手开始。

于 2014-09-24T20:30:18.310 回答