编辑
它实际上是可行的 - 覆盖扩展方法。参考见:How to override an existing extension method。
视图在“ASP”命名空间中创建;因此,为了让您的扩展方法覆盖 System.Web.Mvc.Html(即静态类 InputExtensions)中的默认扩展方法,您还必须在“ASP”命名空间中声明您的覆盖。因此,在您的 MVC 项目中,像这样定义类 InputExtensionOverride.cs:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
namespace ASP {
public static class InputExtensionsOverride {
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {
return InputExtensionsOverride.TextBoxFor<TModel, TProperty>(htmlHelper, expression, (string)null);
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {
return InputExtensionsOverride.TextBoxFor<TModel, TProperty>(htmlHelper, expression, (string)null, htmlAttributes);
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {
var dictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return InputExtensionsOverride.TextBoxFor<TModel, TProperty>(htmlHelper, expression, (string)null, dictionary);
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string format) {
return InputExtensionsOverride.TextBoxFor<TModel, TProperty>(htmlHelper, expression, format, ((IDictionary<string, object>)null));
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string format, IDictionary<string, object> htmlAttributes) {
htmlAttributes = SetCommonAttributes<TModel, TProperty>(htmlHelper, expression, ref htmlAttributes);
return System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, format, htmlAttributes);
}
private static IDictionary<string, object> SetCommonAttributes<TModel, TProperty>(HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, ref IDictionary<string, object> htmlAttributes) {
if (htmlHelper == null) {
throw new ArgumentNullException("htmlHelper");
}
if (expression == null) {
throw new ArgumentNullException("expression");
}
if (htmlAttributes == null) {
htmlAttributes = new Dictionary<string, object>();
}
if (!htmlAttributes.ContainsKey("class")) {
htmlAttributes.Add("class", "form-control input-sm");
}
return htmlAttributes;
}
}
}
在您看来没有变化 - 即:
@using (Html.BeginForm()) {
@Html.TextBoxFor(m => m.SomeProperty)
}
将使用您的“form-control input-sm”css 类生成文本框。