Chapter 6. Advanced Techniques

Chapter 2 introduced you to two ways to create reusable markup: Partial Views and Razor Helpers. Then Chapter 5 introduced you to the components that make up the Razor API and how they work together to help turn Razor templates into classes that render HTML to website visitors.

For most projects, partial views and Razor Helpers are all you need; however, some circumstances require a bit more customization. This chapter shows how to take the Razor API to the next level with several techniques that can help make application development with Razor templates quite a bit easier.

Inline Templates and Templated Delegates

Razor Helpers are an effective way to expose reusable code and markup as methods that the views in your application can share. Even though the Razor Helper syntax is pretty straightforward, Templated Delegates offer an even easier approach for accomplishing the same result, just with a different syntax.

As a reminder, here is an example snippet of a Razor Helper that renders an <li> list item:

@helper ListItem(string content) {
    <li>@content</li>
}

<ul>
    @foreach(var post in Posts) {
        @ListItem(post.Title)
    }
</ul>

And this is the same snippet as a Templated Delegate:

@{
    Func<dynamic, HelperResult> ListItem = @<li>@item</li>;
}

<ul>
    @foreach(var post in Posts) {
        @ListItem(post.Title)
    }
</ul>

The Templated Delegate is defined in a code block as a Func<dynamic, HelperResult> delegate, which is then called later in the markup. At first glance, there is ...

Get Programming Razor now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.