Templated delegates

The templated delegates functionality in Razor allows you to define a piece of markup and then have it used to represent a specific object on the page. This is a great tool when you need to represent e.g. one of your classes in multiple places inside of your View. It can also be a great way to separate a large chunk of markup from the logic of your View which can make it easier to read and maintain large Views.

When defining a templated delegate, you will be using a Func delegate - it could look like this:

In this first half, before the equal-sign, I create the movieTemplate delegate. In the second part, I specify the markup template to be used. Notice that I use a variable called item - it's passed into the delegate and the type is dynamic, meaning that I can access members on it (e.g. Title) which are not checked at compile-time. Instead, they are validated at runtime, where they are expected to exist on the object passed to the delegate - if not, an exception will be thrown! I intennd on passing in objects of the type Movie, a simple class we used previously in this tutorial:

So, with our templated delegate in place, we can now use it, e.g. inside a loop. Notice how I can now just call the delegate and pass in the Movie object, instead of defining the markup inside the loop:

@foreach(var movie in movies){ @movieTemplate(movie)}

When populating the movies collection, used in the loop, with some test data, the generated output will look like this: