MVC HTML Helpers and Lambda Expressions

Before I answer your 2 bullet points, I think you need to understand what lambda expressions actually are.

In .Net, Lambda expressions used in this way are what is called Expression Trees. From MSDN:

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

These are essentially data structures that describe what is being passed in rather than the values of the data being passed in. What this means is that when you call Html.DisplayFor(x => model.Name) it is passing in a data structure that says “I am calling this method for the Name property of the xxxx data structure (where xxxx is the type of data structure that represents your View Model).

The DisplayFor then looks at this data and sees that the property name Name is well Name, it looks at all attributes for the property to find out if you have any data annotations attached to it, and then looks at the value to determine how to represent the display for the value. It’s a bit complicated until you get your head wrapped around it, but once you look at the MSDN page and think about it you will have an aha! moment like I did, and it will just suddenly make sense 🙂

As to your question #1, the advantage of using lambda expressions is you get compile time checking of your properties. For example, if you rename ViewModel.Name to ViewModel.ClientName, all your Html.DisplayFor(x => model.Name) won’t compile, thus making sure you change them. If you don’t use lambda expressions, all your Html.Display() calls will work, but you will get hidden bugs with model binding that will not be immediately obvious of what’s wrong.

To answer #2, the reason is the same as my description of expression trees. Without using lambdas, you are just passing in the value of Model.Name with no information about the property itself, so it doesn’t know the name of Model.Name property is Name, all it sees is the string value.

Another good write-up of Expression Trees can be found here. Understanding expression trees opens up a whole lot of power in .Net 🙂

Leave a Comment