Creating a custom View Engine for ASP.NET MVC leveraging Text Template (T4) engine for rendering the view

This post explains how to create a View Engine for ASP.NET MVC, leveraging the Text Template (T4) infrastructure already out there for rendering the view based using a custom T4 template host.

Clarification: Here, I’m not using T4 for design time code generation. We are using T4 toolkit to render the views during runtime.

[+] Download Related Source Code

For me, the most beautiful aspect of ASP.NET MVC is it’s extensibility – they way you can ‘stretch’ the framework, to make it suitable for your own needs. I highly recommend you to read this article from Code Climber’s blog – 13 ASP.NET MVC Extensibility Points you have to know

In this post, we’ll explore the following concepts.

  • ViewEngines in ASP.NET MVC
  • Creating a custom ViewEngine for ASP.NET MVC
  • Supporting multiple View Types (our view engine will support both aspx/ascx files and tt files)
  • Partial rendering between view types (you can render a tt view from an aspx view)

Preface About View Engines

This is a quick recap on how the View Engine is invoked with in the ASP.NET MVC Framework. Let us start from how a controller is created and how an action is called. I’m going the easy way – the route handling system in ASP.NET MVC invokes a DefaultControllerFactory by default, which is responsible to choose the correct controller class and an action for a given request. For example, consider the URL – As you know, by default, MVC will expect a CustomerController class with a Get Action inside the same, like

  1. public class CustomerController : Controller
  2. {
  3. public ActionResult Get(int id)
  4. {
  5. //Get the customer with ID from repository, place it in ViewData
  6. ViewData[“Customer”] = rep.GetCustomerWithId(id);
  7. //View method returns a Viewresult
  8. return View();
  9. }
  10. }

imageThe controller will invoke the correct action method, which returns an ActionResult object. In the above example, you may see that we are returning a ViewResult. In ASP.NET MVC, there are various action results, including ViewResult,ContentResult etc.

Wow, There we are. If the controller action is returning a ViewResult, the action method can use the ViewData structure (see the above example) to fill it with some values, to pass the same to ViewResult. ViewResult can locate and render a particular view template using ViewData. It does so by invoking WebFormViewEngine.

The default View engine available with ASP.NET MVC is WebFormViewEngine, which creates a WebFormView to render your aspx and ascx files. The View Engine normally passes the path information of the file to render, along with the view context information to the view.

The view file name and path is normally detected based on convention – normally in the path –/Views/{ControllerName}/{ActionName} – i.e, If your Controller class name is CustomerController and action/method name is Get, the default view engine will expect a file in the location /Views/Customer/Get.aspx

Using Text Template Toolkit To Render A View

The beauty of ASP.NET MVC is in it’s extensibility. All interaction points above can be customized the way you like. As of now, we are only interested to see how to create a custom View Engine, which can create a T4View that knows how to render a text template (tt) file, leveraging the Text Templating infrastructure.

Normally, as you are aware, Text Templates (T4) are used with in Visual Studio for activities like Code Generation. When I was going through this exercise of explaining how to create a custom view engine for ASP.NET MVC, I thought it’ll be an interesting exercise to leverage T4 toolkit for the task.

But we’ve got a problem there – We can’t use the Microsoft.VisualStudio.TextTemplating libraries, because I don’t believe that T4 can be legally redistributed without Visual Studio. So, I’ve decided to relay on the Mono equivalent T4 implementation, Mono.TextTemplating (included in the download)

Now, let us get in to the actual task. These are the steps we should do to create our view engine.

  • A ViewEngine implementation
    • We’ll create a view engine by implementing the IViewEngine interface. There is an abstract classVirtualPathProviderViewEngine that already implements IViewEngine interface and provides some extra functionality for path detection of view files.  VirtualPathProviderViewEngine  has two methods we are concerned about – CreateView and CreatePartialView from where we should return a custom View, that has the path information to the template file (*.tt) to render.
  • A View
    • We’ll create a view, by implementing the IView interface. IView has a Render method that we are interested about. We’ll read and render the tt file, leveraging the TT engine
  • A T4 Host
    • We’ll also create a custom T4 host, by implementing the ITextTemplatingEngineHost interface, for self hosting the template transformation process.

Once we’ve the above pieces, we need to register our custom view engine with ASP.NET MVC. That’s pretty simple, and we’ll see that soon.

The View Engine Implementation

imageMay be it is time to have a look in to the actual view engine implementation. A slight variation to what we discussed earlier. Instead of creating a ViewEngine from scratch, we are going to inherit our ViewEngine fromVirtualPathProviderViewEngine that’s already there in MVC framework – so that all the file path logic will be taken care automatically. VirtualPathProviderViewEngine provides some extra functionality so that we can specify the location formats to look for our view files (in this case, *.tt files), when ever the View Engine is invoked.

Alright. Let us be a bit more creative here. What about creating a View Engine that can handle the aspx and ascx files *along with* the text template files? Creating such a composite view engine is pretty simple – So, this is what our view engine should do.

  • First, the view engine should look for a View file that ends with *
    • If that file exists, create and return a T4View that’ll render our tt file
    • If not, look for a View file that ends with *.ascx or *.aspx
      • If exists, create and return a WebFormView that knows how to render the aspx/ascx files.

Enough blabbering. Here we go, the code of our CompositeViewEngine. All the implementations are inMvcT4ViewEngine.Lib project, so you may download the related source code from the above link to have a look at the same side by side.

  1. /// <summary>
  2. /// A composite view engine to help plugging view engines
  3. /// </summary>
  4. public class CompositeViewEngine : VirtualPathProviderViewEngine
  5. {
  6. // Ctor – Let us set all location formats
  7. public CompositeViewEngine()
  8. {
  9. base.MasterLocationFormats = new string[] { “~/Views/{1}/{0}.master”,
  10. “~/Views/Shared/{0}.master” };
  11. base.AreaMasterLocationFormats = new string[] { “~/Areas/{2}/Views/{1}/{0}.master”,
  12. “~/Areas/{2}/Views/Shared/{0}.master” };
  13. base.ViewLocationFormats = new string[] { “~/Views/{1}/{0}”,
  14. “~/Views/{1}/{0}.aspx”, “~/Views/{1}/{0}.ascx”,
  15. “~/Views/Shared/{0}”,
  16. “~/Views/Shared/{0}.aspx”, “~/Views/Shared/{0}.ascx” };
  17. base.AreaViewLocationFormats = new string[] { “~/Areas/{2}/Views/{1}/{0}”,
  18. “~/Areas/{2}/Views/{1}/{0}.aspx”, “~/Areas/{2}/Views/{1}/{0}.ascx”,
  19. “~/Areas/{2}/Views/Shared/{0}”,
  20. “~/Areas/{2}/Views/Shared/{0}.aspx”, “~/Areas/{2}/Views/Shared/{0}.ascx” };
  21. base.PartialViewLocationFormats = base.ViewLocationFormats;
  22. base.AreaPartialViewLocationFormats = base.AreaViewLocationFormats;
  23. }
  24. /// <summary>
  25. /// Handle the creation of a partial view
  26. /// </summary>
  27. protected override IView CreatePartialView
  28. (ControllerContext controllerContext, string partialPath)
  29. {
  30. if (partialPath.EndsWith(“”))
  31. return new T4View(partialPath);
  32. else
  33. return new WebFormView(partialPath, null);
  34. }
  35. /// <summary>
  36. /// Handle the creation of a view
  37. /// </summary>
  38. protected override IView CreateView
  39. (ControllerContext controllerContext, string viewPath, string masterPath)
  40. {
  41. if (viewPath.EndsWith(“”) && String.IsNullOrEmpty(masterPath))
  42. {
  43. return new T4View(viewPath);
  44. }
  45. else if (viewPath.EndsWith(“”) && !String.IsNullOrEmpty(masterPath))
  46. {
  47. return new T4View(viewPath,masterPath);
  48. }
  49. else
  50. return new WebFormView(viewPath, masterPath);
  51. }
  52. /// <summary>
  53. /// Check if the file exists
  54. /// </summary>
  55. protected override bool FileExists
  56. (ControllerContext controllerContext, string virtualPath)
  57. {
  58. return base.FileExists(controllerContext, virtualPath);
  59. }
  60. }

That looks pretty simple, right? Have a look at the constructor, and you’ll find that we are specifying the path format constraints to detect our T4 view files as well (*, along with the aspx and ascx path formats. And you may also find that in the CreateView and CreatePartialView, we are creating and returning a WebFormView, in case the * files are not found. CreatePartialView will be invoked when a partial rendering is requested – e.g. when the user calls a RenderPartial method in a view.

Now, the interesting aspect there is, you can render a text template view from an aspx view, using the Ht

The View Implementation

The T4View implementation is also very simple. We are just invoking our T4 host, to render the tt files. Have a look at the Render method below. You may also note that we are passing the ViewContext to the host, so that we can access the view context later in our text template files, via the host variable.

  1. /// <summary>
  2. /// A view based on T4
  3. /// </summary>
  4. public class T4View : IView
  5. {
  6. #region IView Members
  7. private string viewName = string.Empty;
  8. private string masterName = string.Empty;
  9. public T4View(string ttViewName)
  10. {
  11. viewName = ttViewName;
  12. }
  13. public T4View(string ttViewName, string masterttName)
  14. {
  15. viewName = ttViewName;
  16. masterName = masterttName;
  17. }
  18. /// <summary>
  19. /// Render our tt file
  20. /// </summary>
  21. /// <param name=”viewContext”></param>
  22. /// <param name=”writer”></param>
  23. public void Render(ViewContext viewContext, System.IO.TextWriter writer)
  24. {
  25. string filePath = viewContext.HttpContext.Server.MapPath(viewName);
  26. string masterPath=string.Empty;
  27. if (!string.IsNullOrEmpty(masterName))
  28. {
  29. masterPath=viewContext.HttpContext.Server.MapPath(masterName);
  30. }
  31. var thost = new T4TemplateHost();
  32. thost[“ViewContext”] = viewContext;
  33. string data = string.Empty;
  34. var results = thost.ProcessTemplate(filePath, masterPath, out data);
  35. if (results.HasErrors)
  36. {
  37. writer.WriteLine(“<h1>errors found</h1>”);
  38. }
  39. foreach (var res in results)
  40. {
  41. writer.WriteLine(“Error – ” + (res as CompilerError).ToString());
  42. }
  43. writer.Write(data);
  44. }
  45. #endregion
  46. }

About the Template Host

You may see that in the Render method, we are creating an instance of our T4 template host, and requesting the template host to process our our * file. You may read more about creating a custom template host here, though I’m not detailing that much. How ever, if you are so curios, here is the ProcessTemplate method in our custom T4 host.

  1. /// <summary>
  2. /// Process the input template
  3. /// </summary>
  4. /// <returns></returns>
  5. public CompilerErrorCollection ProcessTemplate
  6. (string templateFileName, string masterFileName, out string data)
  7. {
  8. if (!File.Exists(templateFileName))
  9. {
  10. throw new FileNotFoundException(“The file cannot be found”);
  11. }
  12. var engine = new TemplatingEngine();
  13. TemplateFile = templateFileName;
  14. //Read the text template.
  15. string input = File.ReadAllText(templateFileName);
  16. if (!string.IsNullOrEmpty(masterFileName))
  17. {
  18. input = File.ReadAllText(masterFileName).Replace(“<!–[Content]–>”,input);
  19. }
  20. //Transform the text template.
  21. data = engine.ProcessTemplate(input, this);
  22. return Errors;
  23. }

Registering our View Engine

The last piece of the puzzle would be to register our custom View Engine, so that the framework will use our View Engine instead of the default one. Let us create a new ASP.NET MVC Project. Now in the Global.asax.cs file of our MVC application (See MvcT4ViewEngine.Demo project in the downloaded source code), we need to specify our CompositeViewEngine as the default view engine, in the Application_Start.

  1. protected void Application_Start()
  2. {
  3. ViewEngines.Engines.Clear();
  4. ViewEngines.Engines.Add(new CompositeViewEngine());
  5. RegisterRoutes(RouteTable.Routes);
  6. }

And there we go.


The Results

First of all, let us add a new GetMessage method to the HomeController ASP.NET MVC project. Our GetMessage action in the Home controller simply returns a view after storing someting in ViewData, like

  1. public ActionResult GetMessage()
  2. {
  3. ViewData[“MessageForT4”] = “Welcome to ASP.NET MVC Views using T4”;
  4. return View();
  5. }

Now, add a new view, named in the Views/Home folder as shown below. And you can access the ViewData like this.


Now, run the application, and navigate to the path /Home/GetMessage and you should be able to see the above view getting rendered. If you are wondering what the GetViewData method does, it fetches the ViewData context we set to the host earlier, in the above Render method.



More interestingly, you may also try partially rendering a T4 view from an aspx file. You can useHtml.RenderPartial(“YourView”); from your aspx view, to render the file – See how I’m from the Index.aspx view, in the attached example.


The intent of this article is just to explore how to create custom view engines for ASP.NET MVC. The example view engine we put together is very elementary as of now, but I’ld like to evolve that towards something useful, so that finally it can be a part of MvcContrib. For this, several performance features like caching of compiled views needs to be implemented. That is for later.

Recommending you to follow me on twitter – Also, read my previous posts – A duck typed view model in ASP.NET MVC or Understanding Managed Extensibility Framework and Lazy<T> – Happy Coding!!


About Nguyễn Viết Hiền

Passionate, Loyal
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s