Jan
Jan

Reputation: 8131

How to make a custom strongly typed html helper method?

Now I found out how to create custom html helpers

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

Now how to turn it into a strongly typed helper method InputFor Like it is in the framework?

I don't need the Html.TextBoxFor method, I know it exists. I am just curious in how to implement this behavior myself and used this as a simple example.

PS. I was looking in the mvc source code but couldn't find a trace of this mysterious TextBoxFor. I only found TextBox. Am I looking at the wrong code?

Upvotes: 3

Views: 2066

Answers (1)

Lorenzo
Lorenzo

Reputation: 29427

Here you can find the ASP.NET MVC 2 RTM Source code.

If you look at the InputExtensions class inside the System.Web.Mvc.Html namespace you will find the following code

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

Upvotes: 4

Related Questions