Videos | Podcasts

Using T4 Templates to Create Strongly Typed View Names
AzamSharp
Published Date: 1/11/2010 1:55:19 PM
Views: 1494

Abstract:
In ASP.NET MVC application we use the View method to render the view. The View method takes the name of the view as a parameter and then renders that view. The use of string as a parameter for view opens it up for errors as anyone can misspelled the name and cause the MVC framework to load a non-existent view. In this article we are going to use the T4 templates to create strongly typed view names.

Scenario:

Let's say you are working on an ASP.NET MVC application. You are using the view name as string to pass to the View method which is responsible for rendering the view. The view you are working on is called Register. You use the following code to render the view.


 public ActionResult Index()
        {
            return View("Register");          
        }


This will render the Register view correctly. If you accidentally typed the following it won't work.


 public ActionResult Index()
        {
            return View("Registar");          
        }


The only way to see the error in action is to run the page. This is because the mistyped view name is not an error when the application is build. The error only triggers when the application is in running state.

It would be nice if we have a list of options that represents the available views. In the next section we will demonstrate how to use the power of T4 templates to autogenerate the classes for each view folder.

Implementing T4 Magic:

If you are not familiar with T4 templates then you should definitely check out the following article.

Code Generation Using T4 Templates

Our T4 template is responsible for building classes and fields associated with the View. Take a look at the following structure:


public static class ViewFolderName  
{
   public const string ViewName = "ViewName";
}
 


This means that if your view folder name is "Home" which contains the "About.aspx", "Index.aspx" view pages then the following class is generated.



public static class Home
{
   public const string About = "About";
   public const string Index = "Index";
}



And you can access the view in your controller using the following code:

public ActionResult Index()  
{
   if(loadAboutView)
   {
     return View(Home.About);
   }
}


Here is the complete T4 template file which makes this happen:


 
<#@ template language="C#" debug="True" hostspecific="True" #>
<#@ output extension=".cs" #>

<#@ assembly name="System.Web" #>
<#@ assembly name="System.Web.Mvc" #>


<#@ import namespace="System.Web.Mvc" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Web" #>


using System;

namespace StronglyTypedViews
{

    <#
    
     string viewsFolderPath = @"C:\Projects\LearningASPMVC\LearningASPMVCSolution\LearningMVC\Views";
    
     string[] folders = Directory.GetDirectories(viewsFolderPath);
         
    
     foreach(string folderName in folders)
     {
    
     #>
    
     public static class <#= System.IO.Path.GetFileName(folderName) #> {            
     <#     
      foreach(string file in Directory.GetFiles(folderName))       {
         #>          
         public const string <#= System.IO.Path.GetFileNameWithoutExtension(file) #> = "<#= System.IO.Path.GetFileNameWithoutExtension(file).ToString()  #>";
          
     <# } #>
    
     }
    
    <# } #>
             
        
}



The viewsFolderPath is used to store the path to the views root folder. Then we iterate through the views root folder and retrieve all the views. Each view is constructed as a static class. Then we iterate through the individual view folder and retrieve all the files. Each file is constructed as a const string in the view class.

The result is shown below:


 public static class Home {            
               
         public const string About = "About";          
               
         public const string Confirm = "Confirm";          
               
         public const string Index = "Index";          
               
         public const string Register = "Register";          
         
     }
    


The screenshot below shows the effect in action:



Refreshing T4 Template:

Occasionally, you will require to refresh the T4 template to reflect the changes in the Views folder. This happens when you add, remove or rename the view. The T4 template is refreshed automatically whenever it is saved. This means whenever you save the .tt file it is executed which builds the .cs file.

One of the problems is that you have to be inside the T4 file in order for it to be refreshed. The "Save All" option does not have any effect on the T4 file and it is not executed. You can write some PreBuild task which can do a force save on all the T4 files but that topic is not covered in this article.

Conclusion:

In this article we learned how to use T4 templates to generate our view names. This technique allows us to catch the errors at compile time rather than at runtime.

[Download Sample]



Did you like this article?
kick it on DotNetKicks.com Submit
Similar Articles

Implementing Blog Using ASP.NET MVC and MongoDb

Ajaxify your ASP.NET MVC Application

Implementing ViewModel in ASP.NET MVC Application

Creating Wizard in ASP.NET MVC Part 2

Creating Wizard Using ASP.NET MVC Part 1

Enter Comment/Feedback

 
 
 
 
 

Comments/Feedbacks