O'Reilly logo

Professional ASP.NET MVC 4 by Scott Hanselman, K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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> strongTemplate = @<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 to.

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

<div>
     @strongTemplate("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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required