DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Payments Architecture - An Introduction
  • Using Render Log Streams to Log to Papertrail
  • Java String Templates Today
  • Integration Architecture Guiding Principles, A Reference

Trending

  • Payments Architecture - An Introduction
  • Using Render Log Streams to Log to Papertrail
  • Java String Templates Today
  • Integration Architecture Guiding Principles, A Reference

Building Better MVC Code with T4MVC

Michael Ceranski user avatar by
Michael Ceranski
·
Jul. 17, 10 · News
Like (0)
Save
Tweet
Share
9.39K Views

Join the DZone community and get the full member experience.

Join For Free

If you are a ASP.NET web developer than chances are that you have heard of or dealt with problems related to “Magic Strings”. Magic strings are taboo because they introduce a degree of fragility in your code due to the fact that they are not strongly typed. The classic example, is referencing a View Name or Route in your controller action using a string value:

public class HomeController : Controller
{
public ActionResult Index()
{
return RedirectToAction("Foo");
}

public ActionResult Foo()
{

return View();
}
}

As you would expect, when the Index action is invoked the user gets redirected to “Foo”. Unfortunately, if I rename the “Foo” method to “Bar” my code will still compile but it will ultimately fail at runtime. This is all due to the fact that are RedirectToAction method is using the magic string “Foo” which is not strongly typed and therefore not caught by the compiler.

As a workaround to this problem some people have went so far as to declare constants in their code for all the view names and actions. Unfortunately this is not a good solution because there is a great deal of work involved in creating and maintaining all of those constants. So the question becomes “How can I eliminate the magic strings in my code, find errors at compile time, and still make it easy to maintain?”. Well the answer is T4. T4 stands for the Text Template Transformation Toolkit. In the simplest terms, T4 is code that generates code. More specifically in MVC we have the T4MVC template which can be used create strongly typed helpers for referring to your controllers, actions, views, images, scripts and etcetera. For example, with T4MVC the code above can be written as:

public partial class HomeController : Controller
{
public virtual ActionResult Index()
{
return RedirectToAction(MVC.Home.Foo());
}

public virtual ActionResult Foo()
{
return View();
}
}

So now if I rename “Foo” to “Bar” the compiler will catch the error. In addition to making your controller code better, T4MVC also plays an important role in your view pages. For example consider the following snippet of code:

<head>
<title>Magic Strings are BAD</title>
<link rel="stylesheet" type="text/css" href='/Themes/Emporium/default.css' />
<script src="/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<script src="/Scripts/weblog.js" type="text/javascript"></script>
</head>

<%= Html.ActionLink("Delete Contact", "Delete", "Contact", new { id = Model.ContactID })%>

Although this code is perfectly normal we have to be careful if we rename a script or change the name of a controller action because it will break the page. Luckily, T4MVC to the rescue. Here is the same code using T4MVC generated constants:

<head>
<title>Magic Strings are BAD</title>
<link rel="stylesheet" type="text/css" href="<%= Links.Themes.Emporium.default_css %>" media="all" />
<script src="<%= Links.Scripts.jquery_1_4_2_min_js %>" type="text/javascript"></script>
<script src="<%= Links.Scripts.jquery_ui_1_8_1_custom_min_js %>" type="text/javascript"></script>
<script src="<%= Links.Scripts.weblog_js %>" type="text/javascript"></script>
</head>

<%= Html.ActionLink( "Delete Contact", MVC.Contact.Delete( Model.ContactID )) %>

So hopefully by this point you are sold on the idea of using T4MVC in your MVC application. Now its just a matter of configuring it. Fortunately, T4MVC is easy to add to your application. You simply download the T4MVC zip file, extract the templates and drop them in the root directory of your MVC project. Once you include the files in your project the T4 template will execute. The templates will inspect the contents of your application and generate strongly typed references for all the assets within it. After that its just a matter of replacing your magic string references with the T4MVC generated code.

T4MVC was created by David Ebbo and was recently absorbed by the MVC Contrib project which I blogged about a couple of weeks ago. For more information and examples of how to utilize T4MVC in your application visit the T4MVC codeplex page.

Published at DZone with permission of Michael Ceranski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Payments Architecture - An Introduction
  • Using Render Log Streams to Log to Papertrail
  • Java String Templates Today
  • Integration Architecture Guiding Principles, A Reference

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: