2010-12-02 52 views
3

現在我發現瞭如何創建自定義HTML輔助如何製作自定義的強類型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

回答

4

在這裏您可以找到ASP.NET MVC 2 RTM Source code

如果你看一下System.Web.Mvc.Html命名空間中的類InputExtensions你會發現下面的代碼

[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); 
}