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.

No comments:

Post a Comment