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.
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.
This will render the Register view correctly. If you accidentally typed the following it won't work.
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:
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.
And you can access the view in your controller using the following code:
public ActionResult Index()
Here is the complete T4 template file which makes this happen:
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:
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.
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.