Advanced Razor

Chapter 3 highlighted the main Razor features you'll be likely to use in day-to-day work. Razor supports some additional features which, while a little more complex, are really powerful. We think they're worth the effort.

Templated Razor Delegates

In our Razor Layout discussion, we looked at one approach to providing default content for optional layout sections that required a bit of boilerplate code. We mentioned that we could create a better approach using a feature of Razor called Templated Razor Delegates.

Razor has the ability to convert an inline Razor template into a delegate. The following code sample shows an example of this:

@{  Func<dynamic, object> template = @<strong>@item</strong>;}

The delegate that's generated when using a Razor template is of type Func<T, HelperResult>. In the preceding example the type T is dynamic. The @item parameter within the template is a special magic parameter. These delegates are allowed only one such parameter, but the template can reference that parameter as many times as it needs.

With this in place, we can now use this delegate anywhere within our Razor view:

<div>      @template("This is bolded.")</div>

The result of this is that we can write a method that accepts a Razor template as an argument value simply by making that argument be a Func<T, HelperResult>.

Going back to the RenderSection example presented in the Layouts example in Chapter 3, let's do just that:

public static class RazorLayoutHelpers { public static HelperResult ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.