How to create your own strictly typed html helper?

Now I learned 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 InputForLike in the framework?

I do not need a method Html.TextBoxFor, I know that it exists. I'm just curious to know how to implement this behavior and use it as a simple example.

PS. I looked in the mvc source code, but could not find a trace of this mysterious one TextBoxFor. I have found TextBox. Am I looking at the wrong code ?

+3
source share
1 answer

ASP.NET MVC 2 RTM.

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

Source: https://habr.com/ru/post/1778209/


All Articles