Creating MVC3 Razor views from a T4 Template

by david 2. November 2011 22:09

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",
      "System.Web.dll",
      "System.ComponentModel.DataAnnotations.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.

About the author

David

I'm a C# developer having worked with .Net since it was in beta.  Before that I mainly worked in C and C++.  I have been developing commercial software for more than 20 years.  I also mess around with microprocesors, but that's just for fun.  I live near Cambridge, England and at the moment I'm contracted to one of the departments at Cambridge University.

Tag cloud