Published: 26 Mar 2010
By: Andrew Siemer
Download Sample Code

Andrew Siemer explains how to get rid of magic strings with ASP.NET MVC and T4MVC.

Contents [hide]


If you have worked with ASP.NET MVC at all you are probably aware that the framework allows the use of so called "magic strings". You may wonder why this is something worth mentioning. Some reasons why this topic is important to the average ASP.NET MVC developer is for the most part those magic strings reference controller names, action names, area names, and possibly other types in your code. As long as nothing changes in your code these reference should not break. However, every coder knows that the very nature of coding is going to eventually require you to refactor your code including the magic strings that reference your code.


I was going to say "Not even the all-powerful ReSharper is able to parse magic strings and guess at what's what", but in version 4 it is quite able to parse magic strings in ASP.NET MVC and determine how to handle refactoring them when renaming a type. You just can't beat ReSharper!

Visual Studio 2010

One of the big new features of Visual Studio 2010 is the power to refactor in unbelievable ways. It is also able to take a stab and refactoring magic strings and provides a great little window to preview the suggested changes. Magic strings are still evil though!

Add to this the possibility of human error. Typing out class names in a string to be determined at run time is prone to error. These errors are not caught at compile time which means that you need to exercise the code to locate these errors. Now while I have never let one of these types of bugs be deployed to production, I have to admit that coding, debugging, locating a stupid error such as a misspelling, and then repeating the process is a horrible waste of time.

T4MVC to the rescue! This wonderful little bit of code is specifically built to wipe magic strings out of a project. Let's take a look at how this works.

Getting started

The first most important thing to know about the T4MVC project is that it is now part of the MVC Contrib library (created and supported by the good folks at Headspring) which should be your first stop when creating a new MVC project. You can find documentation about T4MVC and locate the most recent download here.


I am using this download at the time of this writing:

Once you have downloaded T4MVC from the MVC Contrib project you can create a new MVC 2 project. With your new project in place, all you need to do is drag your the two files (T4MVC.settings.t4 and into your MVC project (drag the files onto the project itself). Doing this will create some special magic.

First off you will probably see a warning box like this.


Make sure you check the box "Do not show this message again" and click OK. If you don't check the box, each time you build your project, Visual Studio will attempt to execute te templates and prompt you with this warning.

If everything went well you should now see the T4MVC.settings.t4 file and the Notice though that the can now be expanded. It is no longer just one simple file! You now have one file per controller, AccountController.generated.cs, HomeController.generated.cs, and SharedController.generated.cs.

Each time your build your project these generated files will be updated. As you add new areas, controllers, and actions, you will see these generated files update.

Removing the magic strings from the default MVC project

Now let's take a look at how you can use T4MVC in your project. We will take a look at the default MVC project and what is required to remove the various magic strings that come with it. Let's first take a look at the Site.Master file. In it there are a couple of ActionLinks that use magic strings.

Listing 1: Site.Master

To remove the magic strings from the code above we can convert each link using our newly generated helper classes. The default root to drill into the T4MVC is "MVC" (this of course is configurable). This means that where you would normally specify a controller and action you can now say something like MVC.Home.Index() instead which specifies the same information but in a more readable, and strongly typed fashion.

Listing 2: Site.Master

Next we will take a look at upgrading the LogOnUserControl.ascx file. It has references to the Account controller and the LogOff and LogOn actions.

Listing 3: LogOnUserControl.ascx

Let's upgrade these magic strings to strongly typed references.

Listing 4: LogOnUserControl.ascx

The next area to consider for removal of the dreaded magic string is in our routing. Go ahead and open up the Global.asax.cs file. In there is our default route specifications. This also uses magic strings when specifying what routes go where.

Listing 5: Global.asax.cs

Let's get rid of the new { controller = “MagicString” syntax and replace it with T4MVC syntax.

Listing 6: Global.asax.cs

Out of the box there aren't any areas in our project. Let's add one now by right clicking on the project and selecting Add Area. Name this area Test. You should then have an Areas folder inside of which is a Test folder. This new Test area has its own Controllers, Models, and Views. It also has a TestAreaRegistrion.cs file which wires in the area to our Routing dictionary.

Before we can do anything to futz around with our new Area, we first need to add a controller and a view. Right click on the controllers folder and select add controller. I am going to name mine Controller1Controller. Fancy, I know. This new controller file will already have an Index action specified in it. Right click on the View() and select Add View. Click Add. Build your project.

This now gives us enough to play with in our area. Now we can configure our new view to be the default view for this area. Open up the TestAreaRegistation.cs file so we can upgrade it to our new T4 syntax. Inside of this file you will see that a new route is already added like so.

Listing 7: TestAreaRegistration.cs

This can be changed with the same syntax as before. Simply start typing MVC. ...uh oh. The area doesn't show up when we try to dot our way through. To fix this simply build your project.

Listing 8: TestAreaRegistration.cs

Now go back to your Site.Master file. Let's add one more navigation button to our menu that will link us into our new area.

Listing 9: Site.Master

Now run your project to see that it works just as it once did. Then navigate to your area to make sure that that is wired up as you would like it to be. Once you were able to verify that your project runs as expected, let's do a little test to see if all of this was worth the trouble. Go to your HomeController and press [ctrl+r] + [r] which should allow you to use Visual Studio to rename the action (method) name. This should present you with a box to preview your suggested changes and then apply them.

Keep in mind that we did not change the magic strings in the AccountController that reference our HomeController.Index action to T4MVC so depending on how your go about refactoring the Index action you may end up with varying results.


Now that we have converted our default MVC project to use T4MVC you should have a handle on how it might apply to your project. More importantly you can now see the power of T4MVC by attempting to rename your Index action. But no matter what tools you use to refactor your code, whether they work with magic strings or not, you should also consider the readability of your code when looking at the T4MVC syntax compared to the magic string syntax. Readability and ease of refactoring are very important to the creation of a stable maintainable code base. And now that T4MVC has been moved into MVC Contrib you should also feel pretty safe including T4MVC in your project as it should be well supported by the folks over at Headspring!

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Andrew Siemer

I am a 33 year old, ex-Army Ranger, father of 6, geeky software engineer that loves to code, teach, and write. In my spare time (ha!) I like playing with my 6 kids, horses, and various other animals.

This author has published 29 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category

Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.

You might also be interested in the following related blog posts

Html Encoding Nuggets With ASP.NET MVC 2 read more
MvcContrib working on Portable Areas read more
MvcContrib version control has moved to GitHub read more
You should NOT use ASP.NET MVC if. . . read more
MvcContrib v1.0 Released! Download now read more and Two Views of ASP.NET MVC Views read more
MvcContrib Release Candidate posted to CodePlex - now with more consolidated packaging read more
ASP.NET MVC Release Candidate 2 read more
Donut Caching in ASP.NET MVC read more
An Arbitrary Cycle Method For ASP.NET MVC read more

Please login to rate or to leave a comment.