现在我发现了如何创建自定义html助手
using System;
namespace MvcApplication.Helpers {
public class InputlHelper {
public static string Input(this HtmlHelper helper, string name, string text) {
return String.Format("<input name='{0}'>{1}</input>", name, text);
}
}
}
现在如何将其转换为强类型辅助方法InputFor
就像它在框架中一样?
我不需要Html.TextBoxFor
方法,我知道它存在。我只是对自己如何实现这种行为感到好奇并将其用作一个简单的例子。
PS。我正在查看mvc源代码,但找不到这个神秘TextBoxFor
的痕迹。我只找到了TextBox
。我看错了code吗?
答案 0 :(得分:4)
您可以在这里找到ASP.NET MVC 2 RTM Source code。
如果查看InputExtensions
命名空间内的System.Web.Mvc.Html
类,您将找到以下代码
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {
return htmlHelper.TextBoxFor(expression, (IDictionary<string, object>)null);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {
return htmlHelper.TextBoxFor(expression, new RouteValueDictionary(htmlAttributes));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {
return TextBoxHelper(htmlHelper,
ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model,
ExpressionHelper.GetExpressionText(expression),
htmlAttributes);
}