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