0

MVC2 Areas, T4MVC and sharing actions

Posted April 29th, 2010 in Software Development and tagged by cody

Using T4MVC: T4 templates to rid your MVC2 application of “magic strings”, strings representing action, controller and view names, can be extremely useful in making your code much more stable. It can help eliminate run-time errors and instead will generate compile errors notifying you that you have a reference to an action or view that doesn’t exist. Allowing you to do the following:

[HttpGet]
public virtual ActionResult LogOn()
{
	return View(Views.LogOn);
}

As opposed to:

[HttpGet]
public virtual ActionResult LogOn()
{
	return View("LogOn");
}

This post is not going into T4 templates, if you are not familiar with them check out Code Generation and Text Templates for an overview. Using them can present some challenges though and one of those is what I will be addressing in this post.

The Challenge

If you are using areas in your MVC application and you have functionality that crosses those boundaries, T4 templating causes issues when that logic needs to display views or redirect to actions for each area.

The easy solution is to have a controller that encapsulates the logic that both areas use but then you have to resort to magic strings and this could result in run-time errors if a view or action is moved or renamed later.

The Solution

What we did was simply use an abstract base controller that resides in the main controller folder of the project and created derived classes in the respective areas. The base class is where all the common logic exists and the derived classes implement the desired logic and displays the area specific views.

For example:
(In base class)

public abstract ActionResult Index();

(In derived class1)

[HttpGet]
public override ActionResult Index()
{
	return View(MVC.MainArea.Home.Views.Index, null);
}

(In derived class2)

[HttpGet]
public override ActionResult Index()
{
	return View(MVC.OtherArea.Home.Views.Index, null);
}

This allows the application to use the T4 templates and still generate compile time errors if someone changes any views or actions referenced in the derived controllers.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Leave a Reply