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.