Hello, T4MVC – Goodbye, ASP.NET MVC “magic strings”
Posted
by Brian Schroer
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Brian Schroer
Published on Sun, 06 Jun 2010 05:47:02 GMT
Indexed on
2010/06/06
13:02 UTC
Read the original article
Hit count: 491
I’m working on my first ASP.NET MVC project, and I really, really like MVC.
I hate all of the “magic strings”, though:
<div id="logindisplay">
<% Html.RenderPartial("LogOnUserControl"); %>
</div>
<div id="menucontainer">
<ul id="menu">
<li><%=Html.ActionLink("Find Dinner", "Index", "Dinners")%></li>
<li><%=Html.ActionLink("Host Dinner", "Create", "Dinners")%></li>
<li><%=Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
They’re prone to misspelling (causing errors that won’t be caught until runtime), there’s duplication, there’s no Intellisense, and they’re not friendly to refactoring tools.
I had started down the path of creating static classes with constants for the strings, e.g.:
<li><%=Html.ActionLink("Find Dinner", DinnerControllerActions.Index, Controllers.Dinner)%></li>
…but that was pretty tedious.
Then I discovered T4MVC (http://mvccontrib.codeplex.com/wikipage?title=T4MVC).
Just add its T4MVC.tt and T4MVC.settings.t4 files to the root of your MVC application, and it magically (and this time, it’s good magic) generates code that allows you to replace the first code sample above with this:
<div id="logindisplay">
<% Html.RenderPartial(MVC.Shared.Views.LogOnUserControl); %>
</div>
<div id="menucontainer">
<ul id="menu">
<li><%=Html.ActionLink("Find Dinner", MVC.Dinners.Index())%></li>
<li><%=Html.ActionLink("Host Dinner", MVC.Dinners.Create())%></li>
<li><%=Html.ActionLink("About", MVC.Home.About())%></li>
</ul>
</div>
It gives you a strongly-typed alternative to magic strings for all of these scenarios:
- Html.Action
- Html.ActionLink
- Html.RenderAction
- Html.RenderPartial
- Html.BeginForm
- Url.Action
- Ajax.ActionLink
- view names inside controllers
But wait, there’s more!
It even gives you static helpers for image and script links, e.g.:
<img src="<%= Links.Content.nerd_jpg %>" />
<script src="<%= Links.Scripts.Map_js %>" type="text/javascript"></script>
…instead of:
<img src="/Content/nerd.jpg" />
<script src="/Scripts/Map.js" type="text/javascript"></script>
Thanks to David Ebbo for creating this great tool.
You can watch an eight and a half minute video about T4MVC on Channel 9 via this link: http://channel9.msdn.com/posts/jongalloway/Jon-Takes-Five-with-David-Ebbo-on-T4MVC/.
You can download T4MVC from its CodePlex page: http://mvccontrib.codeplex.com/wikipage?title=T4MVC.
© Geeks with Blogs or respective owner