T4MVC for removing magic strings from Razor views.

If you haven’t used T4MVC before, it’s a very nice NuGet package that helps remove some of the ‘magic strings’ from MVC views. Normally, you would create a link to a controller action in razor like this;

@Html.ActionLink("Link Text",
    "Development", "ChangeConnectionString", new { connectionString= "DataSource=foo" })

Which assumes there is a DevelopmentController with an action method like;

ActionResult ChangeConnectionString(string connectionString) 

T4MVC is a T4 (text templating) file which scans all your controllers and makes strongly-typed methods for specifying the controlller, actions, and parameters, which you use like this;

@Html.ActionLink("Link Text", 

Notice how we’ve removed the magic strings for the controller name and method name, and made the parameters more compact. If an action method name changes, or the parameter signature changes, T4MVC’s methods now stop compiling, and you get compile-time errors in your views, rather than runtime errors.

T4MVC needs to be run whenever a controller is added or an action method signature changes. This can be easy to forget, so I recommend the AutoT4MVC extension.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s