Step By Step Implementing t4 Custom Templates in MVC5 Project

Let’s first understand what a t4 template is

T4 templates are the sample code written in the files, this may be View code / controller code / web config code. Whenever you create the MVC project, Controller, View automated code is written by Visual Studio. This code is referred from these templates. If you modify this template code your sample code will get modified (for next time you create the code).

Where is the location of t4 template in MVC 5 or Visual Studio 2015 ?

C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates

Note: folder name might be depending on your OS, Visual studio Version for VS2015 it will be Microsoft Visual Studio 14.0,

folder

If you look at the folder, you will find the templates for View, Controller, and even webconfig file.

You may open the file but note if you change these files here then there change will be applied to each and every project you are going to create. So it will be better to change these templates specific to your project

Let’s start with step wise creating the custom t4 template for your project,

Step 1: Create a sample project.

Step 2: Create a separate CodeTemplate folder in your solution folder and copy everything from template folder (C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates ) in to your CodeTemplate and include everything in the solution.

solution

Step 3: Build your solution.

Step 4: Do some modification in template as an example I modified MVCViewWithoutModel >> Empty.cs.t4 in header part and added <b></b> tag

.cs.t4 represent for csahrp project.
.vb.t4 represent for VB project file.

MVCViewWithoutModel represent changes will be impacted when creating View without model

Tag to the header

tag

Step 5: Save the changes and build the project.

Step 6: Create the controller and add sample action.

sample

Step 7: Right click on action to add sample view,

view

Step 8: You will find what are the changes you had done in t4 template will get affected into the empty view created by you.

template

I hope you enjoyed this article. Added code sample will help you to understand in more detail.