DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Basic Introduction about T4 Templates & How to customize them for ASP.NET MVC Project

Basic Introduction about T4 Templates & How to customize them for ASP.NET MVC Project

Ovais Mehboob Ahmed Khan user avatar by
Ovais Mehboob Ahmed Khan
·
Nov. 25, 12 · Interview
Like (0)
Save
Tweet
Share
12.17K Views

Join the DZone community and get the full member experience.

Join For Free

in asp.net mvc 3 you can easily generate views from predefined scaffolding templates provided for create, edit, list, delete and details views out of the box which seems quite riveting. actually, there are some *.tt template files (known as t4 templates) stored at following path c:\program files\microsoft visual studio 10.0\common7\ide\itemtemplates\csharp\web that contains the basic structure and page layout for these views and based on those templates it generates the create, edit, delete, list, details and empty .cshtml or .aspx files depends on which project language you have chosen for asp.net mvc project.

in this post i will discuss about t4 templates and how we can customize by taking a simple example.

what is t4

t4 stands for text template transformation toolkit . t4 generates text based on t ext based template files, t emplate is a combination of text and control logic that you can define using c# or vb.net. t ransformation actually executes the code written in template and brings out a final output whereas the t oolkit contains some assemblies leverage to produce the desire output file.

now, let’s quickly open the sample create.tt file to see what it looks like and how we can customize. when you open the file you can see in the beginning you can see directives

<#@ template language=" c# " hostspecific=" true" #>

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

language specifies which language we are using either c# or vb.net and hostspecific =”true” used only with custom hosts. if you set the value of parameter to true, you can access a property called host in your text template. the property is a reference to the object that hosts the engine. at last, the output extension tells the extension in which the new file this will be generated.

t4 contains 4 types of blocks

-  expression block

used as <#= expression #> , we can write c# or vb.net code but don’t use semi-colon at the end of statement

-  statement block

used as <# code…. #>, define any c# or vb.net code and initialize variables, define loops etc. here we have to specify semi-colon at the end of the code statement just like as we program in a class file.

-  class feature block

used as <#+ code… #> , define methods, classes, properties and constants and can we called from anywhere within the template file. for example, we can create a function that perform some calculation based on the parameters passed and return a boolean through which we can handle the ui designing.

below is the actual page content that dynamically generates the page based on the model attached to it.

@using (html.beginform()) {
    @html.validationsummary(true)
    <fieldset>
        <legend><#= mvchost.viewdatatype.name #></legend>

<#
foreach (modelproperty property in getmodelproperties(mvchost.viewdatatype)) {
    if (!property.isprimarykey && !property.isreadonly && property.scaffold) {
#>
        <div class="editor-label">
<#
        if (property.isforeignkey) {
#>
            @html.labelfor(model => model.<#= property.name #>, "<#= property.associationname #>")
<#
        } else {
#>
            @html.labelfor(model => model.<#= property.name #>)
<#
        }
#>
        </div>
        <div class="editor-field">
<#
        if (property.isforeignkey) {
#>
            @html.dropdownlist("<#= property.name #>", string.empty)
<#
        } else {
#>
            @html.editorfor(model => model.<#= property.name #>)
<#
        }
#>
            @html.validationmessagefor(model => model.<#= property.name #>)
        </div>

<#
    }
}
#>
        <p>
            <input type="submit" value="create" />
        </p>
    </fieldset>
}
<div>
    @html.actionlink("back to list of main page", "index")
</div>

in the above mentioned code there is if statement that checks whether the property is a foreign key or not and based on that it generates a drop down code otherwise an input control.

let’s create a sample application in asp.net mvc 3 and check it out by customizing a create t4 template.

1.  create a sample project in asp.net mvc3 in visual studio.

2.  create a model class for person and designation. person record contains some basic information and designation holds the list of designations. below is the code first model approach using entity framework ver. 4.3.1.

    public class person	
    {
        public long personid { set; get; }
        public string firstname { set; get; }
        public string lastname { set; get; }
        public string emailaddress { set; get; }
        public string phone { set; get; }
        public long designationid { set; get; }
        public virtual designation designation { set; get; }
  
    }

    public class designation
    {
        public long designationid { set; get; }
        public string designationname { set; get; }
        public virtual icollection<person> persons { get; set; }

    }

3.  create a dbcontext class and define dbset for these entities.

public class dbcontext : system.data.entity.dbcontext, idisposable
{
     public dbset<person> persons { get; set; }
     public dbset<designation> designations { set; get; }
}

4. now create a person controller selecting controller with read/write actions and select person as a model class and db context as you database context class.


5. now if you open the create.cshtml file you will see a drop down list for designation. as in the template file there was a foreign key check. if you run the application form will be shown as below.


6. now let’s change a drop down to list box in the create.tt file.

 <div class="editor-field">
<#
        if (property.isforeignkey) {
#>
            @html.listbox("<#= property.name #>")
<#
        } else {

#>
          is not a foreign key baba: <#= property.isforeignkey #> : @html.editorfor(model => model.<#= property.name #>)
<#
        }
#>
            @html.validationmessagefor(model => model.<#= property.name #>)
</div>

7.  delete the previous controller and generate it again. it will generate a listbox as specified in a tt file.


this was the simple example showing how developers can modify existing templates based on their needs and reduce development time.

hope this helps!

ASP.NET MVC Template ASP.NET Database

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Stream Processing vs. Batch Processing: What to Know
  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • A Real-Time Supply Chain Control Tower Powered by Kafka
  • Promises, Thenables, and Lazy-Evaluation: What, Why, How

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: