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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Designing a Java Connector for Software Integrations
  • Mastering Advanced Aggregations in Spark SQL
  • Is Agile Right for Every Project? When To Use It and When To Avoid It

Building Better MVC Code with T4MVC

By 
Michael Ceranski user avatar
Michael Ceranski
·
Jul. 17, 10 · News
Likes (0)
Comment
Save
Tweet
Share
10.1K 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.

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: