ASP.NET MVC’s scaffolding infrastructure is implemented
using Visual Studio’s built-in T4 templating architecture (Scott Hanselman has
a nice blog post on T4 here).
You can customize/override any of the built-in ASP.NET MVC
scaffold template implementations. You can also create additional
scaffold templates (for example: the “ScottGu Crazy Look” scaffold option) and
have them be displayed as options within the “Add View” dialog.
To customize/add scaffold templates at the machine-wide
level, open the “C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates”
The “AddController” sub-folder contains the scaffold
template for the “Add Controller” dialog. The “AddView” sub-folder
contains the scaffold templates for the “Add View” dialog:
The scaffold templates populated within the
“Add View” dialog are simply text files that have the “.tt” file-name
extension. These “.tt” text files contain inline C# or VB code that
executes when the template is selected.
You can open and edit any of the existing
files to customize the default scaffolding behavior. You can also add new
“.tt” template files – like I have above with the “Scott Crazy Look.tt”
file. When you add a new template file the “Add View” dialog will be
updated to automatically include it in the list of available scaffold options:
In addition to customizing/adding template
files at the machine level, you can also add/override them at the individual
project level. This also enables you to check-in the templates under
source control and easily use them across a team.
You can customize the scaffold templates at a
project level by adding a “CodeTemplates” folder underneath your project.
You can then have “AddController” and “AddView” sub-folders within it:
You can override any of the default
machine-wide templates simply be adding a “.tt” file with the same name to the
project. For example, above we are overriding the default “Controller.tt”
scaffold template used in “Add Controller” scenarios.
You can add new view-template scaffold files
to the list by placing them within the “AddView” folder. For example,
above we added a “Yet Another Crazy Look.tt” view template to our
project. When we use the “Add View” dialog we’ll now see a union of the
templates defined at the machine and project level:
Note: When you add “.tt” templates under the
\CodeTemplates folder make sure to set the “Custom Tool” property of each of
the “.tt” template files to an empty string value within the property grid
(otherwise you’ll get an error trying to run it). You might also need to
close and reopen the project to clear a spurious error from the error
list. We’ll be publishing more blog posts that cover creating/customizing
scaffolding templates shortly.