Thursday, December 31, 2009

How to create Areas in ASP.NET MVC

In ASP.NET MVC we can use the concept of Areas to segregate different functional areas of development into separate projects. This segregation can help make our code easier to maintain - especially among a team of developers because it means that a new programmer potentially has less code to wade through when they come to maintain a specific feature.

In this blog post we will look at how to create an ASP.NET MVC Area and wire it up into our application. To get things started, create a new Visual Studio ASP.NET MVC2 project named AreasDemo

clip_image001

When your project opens up you can see the standard, base ASP.NET MVC project template files are included.

clip_image002

Next we are going to add a new area that will provide the functionality for managing and viewing Favorites. To get things started, add a new ASP.NET MVC2 project to the solution and name it FavoritesArea

clip_image003

Remove all of the content from the FavoritesArea project but leave the Controllers and Models folders

clip_image004

The only things that will live in the *Area projects will be code - Controllers, Routing configuration, Models, and ViewModels. Let's go ahead and create a simple C# class called Favorite which will encapsulate a domain object for our Favorites functional area.

namespace FavoritesArea.Models
{
public class Favorite
{
public string Title { get; set; }
public int Rating { get; set; }
}
}


For this example, we will be creating a single View for our Favorites functional area called Index; the Index view will be the default view for the Favorites functional area and will simply show a list of favorites. Add a Controller class to the FavoritesArea project which looks like so:



public class FavoritesController : Controller
{
public ActionResult Index()
{
var favorites = GetFavorites();
return View(favorites);
}


List<Favorite> GetFavorites()
{
return new List<Favorite>
{
new Favorite { Title = "First Favorite", Rating = 3 },
new Favorite { Title = "Second Favorite", Rating = 5 },
new Favorite { Title = "Third Favorite", Rating = 3 },
};
}

}


Notice that the Index method of this controller class simply returns a hard-coded list of Favorite domain objects.



Next we will add routing information for the Area so that the ASP.NET MVC runtime knows how to access the controller and view for our Favorites function. From within the FavoritesArea project create a new class named Routes - the name is not important but make sure to inherit from the ASP.NET MVC AreaRegistration base class). When you have your Routes class add the following code to it



public class Routes : AreaRegistration 
{
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"favorites_default",
"Favorites/{controller}/{action}/{id}",
new {
controller = "Favorites",
action = "Index",
id = ""
}
);
}

public override string AreaName
{
get { return "Favorites"; }
}
}


The 3 things to take notice of here are:




  1. We've derived from AreaRegistration


  2. We've overridden the RegisterArea method to add our own routing configuration


  3. We've overridden the AreaName property to provide the key name for our Area



Add a reference to the FavoritesArea assembly from the AreaDemo project:




clip_image005




In the Application class of the AreasDemo project, add a line of code which invokes Area registration [1]:



protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}


In the AreasDemo project, create a strongly-typed view named Index and then select your View data class.  In our case, that will be the Favorite domain class that we created earlier.  The view should be added to a folder named Favorites which will live underneath the Views folder.  Therefore the full path to the view file in your Visual Studio project will be /Views/Favorites/Index.aspx.  You cannot see it in the following image (because the Types dropdown is covering it) but you should also select List as the View Content type as this will automatically display our Favorites list for us.




clip_image006




The last thing that we need to do to provide a way for users to navigate to our Favorites Index page.  To do this simply open up the Site.master file and include an additional navigation node for our view.  Notice that you will need to use a different overload of the ActionLink method which lets us specify an area to use.



<div id="menucontainer">

<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About", "About", "Home")%></li>
<li><%= Html.ActionLink("Favorites", "Index", "Favorites", new { area = "Favorites" }, null) %></li>
</ul>

</div>


With these changes made the only thing that remains is to press F5 to run the application and navigate to the Favorites page:




clip_image007




The last thing that you might like to do – for aesthetics – is to place your Area projects into a Solution Folder names Areas.  This again helps maintainability as it makes the structure of the solution much clearer to any potential developers:




image




There you have it!  The code for our Favorites function is now isolated from the main chunk of code which is required to bootstrap the web application.  This will make it easier to maintain, review and test because code can be worked on in a more focused manner.



 






[1] It is important to make the call to AreaRegistration.RegisterAllAreas() prior to calling RegisterRoutes - ASP.NET MVC 2 and why Dynamic Area is not supported.

2010Wave Intro Post

Prior to 2009 I was a very regular blogger.


My first blog started in January 2002 and was hosted on the original DotNetWeblogs service - which later became http://weblogs.asp.net. After that I moved my blogging activity over to http://MarkItUp.com which was (and still is) hosted on some CMS software that I developed whilst writing my book on ASP.NET 2.0 Web Parts back in 2005. After that I turned my attention towards Windows Live and moved across to a Live Spaces blog.


Last year was the first year that I didn't blog since 2001.


This year I have renewed enthusiasm for blogging because I'm geniunely excited by all of the new technologies that I've been playing with. Those technologies include: ASP.NET MVC, Visual Studio 2010, Windows 7, Windows Azure, Windows Mobile, HTML5, Continuous Integration, Software Patterns, DI Containers, Automated Testing, Automated Build Systems, Managing the Release of Software, SharePoint 2010, PowerShell, MSBuild and a host of others.


During the day I'm currently on a 12 month contract with a local Adelaide-based organization where I work as a SharePoint administrator and developer. During this work I'm lucky enough to be considered as a senior member of the team and have been given quite a free license to help improve the way that we develop software. And that's what I'll be blogging about.


During the year I will be diving further into these technologies and plan to post my learnings to this blog. I'm not sure how often I will be posting but I think that I can aim to post about 3-4 quality posts per week on average.


If you would like to follow me you can expect that my posts will lead you on a path towards having more control over your build and release processes for your own software development. Hopefully this will lead to the development of many recipes for bootstrapping development and automating for both on-premise and cloud-based applications.