Creating MVC3 Razor views from a T4 Template

I blogged here about using T4 templates to inspect class properties. I also mentioned in passing that I had used it to create some MVC3 Razor views, so here is an example of that.

The process is essentially the same, except you need to change the output type from your template, like this:

<#@ output extension=".cshtml" #>

To get it to work on a basic model class you'll need to add some extra references, to allow the compiler to do its thing. I've allowed for that by passing in an array of assembly file names. So you can do something like this:

Parser p = new Parser(file, "T4RazorView.Models.HomeModel");
p.AddReferences = getReferences();

...and implement a method which returns them, something like this:

string[] getReferences()
   return new[] {
      "C:\\Program Files (x86)\\Microsoft ASP.NET
      \\ASP.NET MVC 3\\Assemblies\\System.Web.Mvc.dll",

Which is all there is to it. If you add extra properties to the Model, the Razor View will automatically update. So here's an example MVC3 project in Visual Studio 2010 if you're interested.