4/29/2011
Dissecting Razor, part 9: Inline Helpers

In addition to normal and static helpers, Razor supports inline helpers, (also known as templates), which allow you to create lambda expressions that return markup.

An inline helper is created by writing @<tag>Content</tag> as an expression. This creates a lambda expression that takes a parameter called item and returns a HelperResult object containing the markup.

Inline helpers are used to create functions that take markup as parameters. For example, you might make an IfLoggedOn helper that displays content if there is a logged-in user, but shows a login link to anonymous users. To pass the content to the helper, you can use an inline helper:

The @content(currentUser) call in helper method is translated by the Razor compiler into a call to the overload of the Write method that takes a HelperResult (returned from the delegate). This overload writes the content of the HelperResult to the page without escaping it (Just like a call to a normal helper method). Functions that take inline helpers can also get the text rendered by the helper by calling ToString() on the HelperResult.

The IsLoggedOn method is passed a lambda expression that takes an item parameter and returns a new HelperResult. The HelperResult is constructed exactly like a normal helper, except that it’s in a lambda expression instead of a normal method.