MVC 5 Custom View Templates

The out-of-the-box template that comes with Visual Studio has improved a great deal since I first started building ASP.Net Web Pages several years ago. But, as nice as the new template is, it’s still nice to be able to adjust the T4 templates that are used to generate the Views. I’ve known for a long time that I could modify these templates globally, by modifying them directly in the Visual Studio folder, but, it wasn’t until earlier this week that I learned you can customize them for just your single project. This post will demonstrate how to do that. In my next post, I’ll demonstrate how to access the attributes on your Model’s properties, from inside the T4 templates.

For the purpose of this demo, I will be using Visual Studio 2013, MVC 5, EF 6, and .net 4.5.1.

For our sample, we will create a simple application that allows for basic CRUD of a person object. So, fire up NuGet and install EF 6 and add a calls called PersonModel to Models folder:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CustomViewTemplate.Models
{
    [Table("Person")]
    public class Person
    {
        [Key]
        public int PersonId { get; set;}

        [MaxLength(5)]
        public string Salutation { get; set; }
        
        [MaxLength(50)]
        public string FirstName { get; set; }
        
        [MaxLength(50)]
        public string LastName { get; set; }
        
        [MaxLength(50)]
        public string Title { get; set; }
        
        [DataType(DataType.EmailAddress)]
        [MaxLength(254)]
        public string EmailAddress { get; set; }
        
        [DataType(DataType.MultilineText)]
        public string Biography { get; set; }
    }
}

Now, add a basic Person controller, an Empty one so that only the Index Get method is created:

image

namespace CustomViewTemplate.Controllers
{
    public class PersonController : Controller
    {
        // GET: Person
        public ActionResult Index()
        {
            return View();
        }
    }
}

If you right-click inside Index() and choose Add View, use scaffolding to add a List view.

image

Now, the view will open and you’ll see the default List view, which just happens to be a table.

Take special notice to lines 9-11:

<p>
    @Html.ActionLink("Create New", "Create")
</p>

Now, of course this will create a standard issue hyperlink, but what if, for the sake of this example, we want it to be a button instead. Well, we could just change the HTML, but if we wanted this to be a button by default, we would have to change the button. So, first things first, we need to identify the location of the global template files. That location is

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates\

Now, you can modify the .t4 files in this directory, but ONLY do that if you want the changes to be global. To make changes only to the project you are working in, copy the direct to a new folder in your project’s root, called “CodeTemplates”. You only need to copy down the files you will want to change, but it is important that you copy the folder structure down. That is, we want to modify a file called List.cs.t4, so we need to copy our file to “~ProjectFolder~\CodeTemplates\MvcView\List.cs.t4”. So for me, that looks like this:

C:\My Applications\Playground\CustomViewTemplate\CustomViewTemplate\CodeTemplates\MvcView\List.cs.t4

Note, if you are using VB, you’ll want List.vb.t4.

IMPORTANT NOTE
You also need to copy over MvcView\Imports.include.t4 and MvcView\ModelMetadataFunctions.cs.include.t4

Back in Visual Studio, in Solution Explorer, you’ll need to “Show all files”, and do a refresh, but you should see your CodeTemplates folder now. Of course, you won’t need the templates for deployment, but if you are modifying them, you should add to source control, so go ahead and right-click and “Include in project”.

Now, you can open the t4 file, but beware, VS doesn’t come with a T4 editor out-of-the-box. That means, no styling and no intellisense. There are, however, some good T4 editor’s in the VS extensions. I use tangible T4 Editor 2.2.5 plus modeling tools for VS 2013 (free edition). Of course, you’ll need Visual Studio to be closed before you can run the installer.

Remember our hyperlink we want to change to a button, well, there’s no special t4 stuff going on with that, and this isn’t a tutorial on the basics of t4, so with List.cs.t4 open, look for our HTML snippet above and change it to:

<p>
    <button type="button" onclick="addNewPerson();">Create New Person</button>
</p>

Now save the file. Now, back to the controller and right-click inside the Index method, and select AddView and add a new List View, but overwrite the existing one.

Now, when you look at the new version of Index.cshtml, you’ll see that instead of a hyperlink, you now have a button!

Happy Templating!

Advertisements