Professional ASP.NET MVC 4
by Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen, Scott Hanselman
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access