Thursday, April 21, 2011

Razor Inside Templates

In the dot.NET Magazin 4.2011 I wrote an article about Razor, the new view engine that comes with ASP.NET MVC 3. Therefore, it is probably obvious that I worked a lot with Razor. Despite all my work with this amazing new view engine I really love, I just discovered this week another interesting feature which I call the "Razor Inside Templates".

So what is it all about? Let's take a look at an easy example:



Even so this is a very simple example, there are some magic points to look at.

First we define a Func with the parameter type string and get back a return value with the type HelperResult. Instead of the string parameter we could use any type. Even dynamic is an option so we can pass in an anonymous type. This is shown in the next example.



The second magic point is the item object. With the @item it is possible to access the parameter data passed in. Now the basics are clear and we love the inside templates. But is this all or where does this lead us to?

Think of the possibility to write an extension method doing a loop. Instead of just passing in the data, the extension method can accept a template as a parameter. So we could build a WebForms Repeater control. Interesting thought, right?

Let's take a look at the example.


This is the extension method doing the loop by using the template.


And that's how I used the above extension method to list all vendor names from the AdventureWorks database by using a template.

There are many more situation where we can use the inside template feature to build code in a simple and nice way and where we can reuse the functionality because of the templating option.

More about it and how it works under the hood, you can read in this blog by Andrew Nurse.