下面的代码将通过扩展 TextBoxFor 创建一个 CustomTextBoxFor 助手。这使您可以充分利用 MVC 的验证约定,同时打开 htmlAttributes 参数,以便可以根据需要附加更多属性。
public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, string customData)
{
return htmlHelper.CustomTextBoxFor(expression, customData, (IDictionary<string, object>)null);
}
public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, string customData, object htmlAttributes)
{
IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
attributes.Add("data-custom", customData);
return htmlHelper.TextBoxFor(expression, new { data_custom = "customData" });
}
用法:
@Html.CustomTextBoxFor(model => model.MyProperty, Model.CustomData)
@Html.CustomTextBoxFor(model => model.MyProperty, Model.CustomData, new { @class="pretty"})