여기 당신이 원하는 것을 달성하는 간단한 방법입니다. 이 쉽게 여러 속성, 변수 속성 등에 적용 할 수 있습니다
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 헬퍼를 사용하여 시작할 것 같지 않다.
그것은 가치가있는 것보다 더 어려울 것입니다; 자신 만의 TextBoxFor 메서드 나 빈 특성의 HTML을 문질러주는 확장 메서드를 작성해야합니다. –
@ Html.TextBoxFor (m => m.UserName, new {autofocus = ""})라고 생각합니다. 이것은 당신을 위해 작동합니다. –