Quantcast
Channel: Scott Hanselman's Blog
Viewing all articles
Browse latest Browse all 1148

Modifying the default code generation/scaffolding templates in ASP.NET MVC

$
0
0
image

One of the things people like the most about my ASP.NE MVC 2 Ninja Black Belt Tips video, besides the Bill Cosby sweater, is the tip where I show how to modify the default CodeTemplates that are used in Code Generation in ASP.NET MVC (either version).

Eilon mentioned it on an internal mailing list this week so I thought it'd be worth surfacing again in case you haven't heard of this, Dear Reader.

Soon, we'll see even more powerful, flexible, and fun ways to customize your own Scaffolding in ASP.NET MVC 3, so keep an eye out, 'cause it's coming.

Bring the CodeTemplates local to your project

imageWhen you use the Visual Studio "tooling" (that means dialogs and stuff) to Add View or Add Controller, you're actually executing a T4 template and generating a little bit of code. Where does this start and how can you change it?

Try this. Create a new ASP.NET MVC project.

Now, go to:

C:\Program Files (or x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp (or Visual Basic)\Web\MVC (or 2) 3\CodeTemplates

See all those folders? Turns out everything under CodeTemplates are T4 templates that can be either modified in place or even better, can be brought local to your project. Local CodeTemplates will override the global ones.

Copy that folder (or just subfolders like AddController, or AddView) to your ASP.NET project. I do this by dragging from Explorer directly into the Visual Studio Solution Explorer as seen  here:

image

You might get some errors when you drop the folder. Ignore them and instead, select the Templates using Ctrl-Click, then right click and select Properties. (You can delete any templates you won't be using.)

image

Now, see where it says Custom Tool? Clear that string out completely. You're tell Visual Studio that you don't want these T4 Templates to be run during a build. They will only be called manually by the Tooling dialogs like Add View and Add Controller.

You change these templates, or in the case of Add View you can make your own. For example here I've made a new "My Awesome List.tt" as a copy of List.tt and it shows up in the Add View dialog.

image

Now I can not only totally customize what gets generated from the Add Controller and Add View dialogs, I can add custom templates to the drop down. Most importantly, these changes live in the CodeTemplates folder of my project and are carried along with my project in Source Control so others on my team or company can use them as well.

Have you customized yours? Enjoy.

Related Links



© 2011 Scott Hanselman. All rights reserved.



Viewing all articles
Browse latest Browse all 1148

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>