#TIL: T4MVC Templates

It’s been almost a full month since I’ve blogged, and a month and a half since I’ve actually written anything! I blame presentations and new projects at work (and reddit… damn you /r/boardgames!). Regardless, I’ve got a list of TILs and articles I’ve been meaning to write, so look here for the next few days for new content! Today we’ll be talking about T4MVC templates, a neat way to remove those magic strings from your ASP.NET MVC code.

T4MVC is a T4 template that compiles a list of strongly-typed helpers based on your MVC application. This allows you to use the strongly-typed helper methods instead of arbitrary “strings” when you’re referring to actions and controllers in your MVC code and razor templates. Here’s a perfect example:

1
2
3
4
//without T4MVC, you need to type
@Html.ActionLink("Delete Item", "Delete", "Item", new { id = Model.ItemID }, null)
//with T4MVC, this now becomes
@Html.ActionLink("Delete Item", MVC.Item.Delete(Model.ItemID))

I imagine you see the immediate benefit. Now if you ever change your actions or controllers, you’ll immediately get a build error – the compiled helper class will have updated based on your changes, and MVC.Item.Delete wouldn’t be defined. Without T4MVC, you’re faced with the alternative – ctrl+f’ing any instance of “Item” and hoping you find them all before you republish your website.

You can use T4MVC for all sorts of things:

1
2
3
4
5
6
7
8
9
Html.RenderPartial(MVC.Dinners.Views.DinnerForm);

return View(Views.InvalidOwner);

return View(Views.ViewName.Index);

Url.Action(MVC.Dinners.Delete(Model.DinnerID));

routes.MapRoute("UpcomingDinners", "Dinners/Page/{page}", MVC.Dinners.Index(null));

You can get more information and install T4MVC from their codeplex website.

Comments