ASP.NET MVC has a fascination with magic strings. Any time you need to specify an action, a view, or controller, you use a magic string:

return RedirectToAction("Index", "Home", new { id = 4 });
return View("Details");
@Html.ActionLink("Back to details", "Detals", "User", new {id = 12}, new {@class = "backlink"});
@using(Html.BeginForm("Details", "User", FormMethod.Post))

This makes the code really easy to read, of course. But those magic strings, by themselves, don't really mean anything, and they certainly don't catch any errors that might be in them. Did anybody reading this notice that "Details" was misspelled as "Detals" in the third example above?

The problem with magic strings is the same problem that ViewBag has: there's no type checking. The developer won't catch these errors until runtime, and sometimes not at all.

T4MVC aims to remove magic strings from MVC and replace them with strongly-typed instances of ActionResult. It adds a bunch more overloads to methods such as ActionLink(), BeginForm(), and RedirectToAction() so that they can now accept instances of ActionResult as parameters, thereby making them strongly-typed and removing their dependency on magic strings.

Most importantly, it means we can take the above code samples and refactor them to look like this:

return RedirectToAction(MVC.Home.Index(4));
return View(MVC.User.Views.ViewNames.Details);
@Html.ActionLink("Back to details", MVC.User.Details(12), new {@class = "backlink"});
@using (Html.BeginForm(MVC.User.Details(), FormMethod.Post))

Now we don't have any magic strings, and any spelling errors or null reference errors will be caught at compile time rather than runtime.  It also works with methods like Url.Action() and bundles.  Check out the documentation; there's a lot of good tips in there.

T4MVC/T4MVC
T4MVC is a T4 template for ASP.NET MVC apps that creates strongly typed helpers that eliminate the use of literal strings in many places. - T4MVC/T4MVC

T4MVC is available as a NuGet package, so go grab it right now!  I've also got a sample VS2013/MVC5 project over on GitHub that runs standard and T4MVC side-by-side so you can see the comparisons.

exceptionnotfound/T4Sample
Contribute to exceptionnotfound/T4Sample development by creating an account on GitHub.

Happy Coding!