The original release of ASP.NET MVC used HTML helpers with syntax like the following:
These worked, but if you renamed the property in your model (for example, from “” to “”) and forgot to update your view, you wouldn’t catch this error until you actually tried out the page and noticed your model isn’t populating properly. By this time, you might have users using the site and wondering why stuff isn’t working.
ASP.NET MVC 2 introduced the concept of strongly-typed HtmlHelper extensions, and ASP.NET MVC 3 extended this even further. An example of a strongly typed HtmlHelper is the following:
These allow you to write more reliable code, as view compilation will fail if you change the field name in your model class but forget to change the field name in the view. If you use precompiled views, this error will be caught before deployment.
Creating your Own
The built-in helpers are good, but quite often it’s nice to create your own helpers (for example, if you have your own custom controls like a star rating control or rich-text editor). These new helpers are very easy to create, since we can make use of two different classes that come with ASP.NET MVC:
1) — Gets the model name from a lambda expression (for example, returns the “” for the expression , and “” for the expression ). This is what you’d use in the ID and name of the field.
These two classes give us all the information we require to make our own HTML helpers (internally, these are what all the built-in strongly-typed HTML helpers use).
Here’s an example of a simple HTML helper that uses both of the above classes:
public static partial class HtmlHelperExtensions
public static MvcHtmlString NewTextBox(this HtmlHelper htmlHelper, string name, string value)
var Builder = new TagBuilder("input");
Builder.Attributes["type"] = "text";
Builder.Attributes["name"] = name;
Builder.Attributes["value"] = value;
public static MvcHtmlString NewTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return NewTextBox(htmlHelper, name, metadata.Model as string);
Given a model like this:
A view like this:
Will produce HTML like this: