现在,我了解了如何创建自定义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吗?

最佳答案

在这里您可以找到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);
}

09-30 18:11
查看更多