One of the common feature asks people had for ASP.NET MVC 2
was for us to also support strongly-typed HTML helpers that use lambda
expressions when referencing models/viewmodels passed to a view template.
This enables better compile-time checking of views (so that bugs can be found
at build-time as opposed to runtime), and also enables better code intellisense
support within view templates.
New strongly-typed HTML helper methods are now built-into
ASP.NET MVC 2. These methods use a "Html.HelperNameFor()” naming
convention. For example: Html.TextBoxFor(), Html.CheckBoxFor(),
Html.TextAreaFor(), etc. They support using a lambda expression to
specify both the name/id of the element, as well as the value to render for it.
For example, using ASP.NET MVC 2 we can now use the new
Html.TextBoxFor() helper in addition to the Html.TextBox() helper above:
Figure 3
Notice above how we do not need to specify the
“ProductName” string parameter anymore – lambda expressions are flexible enough
that we can retrieve both the name of the property/field on our model object in
addition to its value.
Because the HTML helpers are strongly-typed,
we also get full intellisense support for them within Visual Studio when
writing the lambda expression:
Figure 4
The HTML rendered is the same as the late-bound version of
our HTML helper shown previously:
Figure 5