T4MVC: String-free ASP.NET MVC

One of the few not-so-beautiful parts of ASP.NET MVC is that you have to use strings to refer to your controllers, actions and views. If you ever created an MVC project you probably write something like this into an action:

  return View( "Index" );

or this into a view:

  @Html.ActionLink( "Click here to sign in", "Login" )

The pain points are the strings, because the smallest mistake results a runtime error.

The T4MVC project can help you to solve this problem with strongly typed helpers. The best way to include it into your project is to add it via the NuGet Package Manager:


If you already have controllers in your project, don’t be surprised that the installer will slightly modify them:


And you will get some extra files as well:


But thanks to all that, you can use strongly typed values to refer to views:

  return View( Views.Index );


  @Html.ActionLink( "Bejelentkezés", MVC.Home.Login() )

any many other components – that you can learn more from the documentation.

Because all magic is done via code generation based on T4 templates in the background, you may wonder what happens when you add a new action. You will see that you can immediately use it in your view, it will appear immediately in IntelliSense, but unfortunately it will fail in runtime with the following error (this is the moment when you can think about whether it is not exactly what you wanted to avoid):

T4MVC was called incorrectly. You may need to force it to regenerate by right clicking on T4MVC.tt and choosing Run Custom Tool

Thanks to the perfect error message, if you follow it, your issue will be solved. However, you may find the AutoT4MVC extension more convenient, which monitors your files and folders and automatically regenerates the files when required.


Technorati-címkék: ,

2 thoughts on “T4MVC: String-free ASP.NET MVC

  1. Pingback: lintasblog.com

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s