[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]
This walkthrough illustrates how to create an ASP.NET MVC areas application using a Visual Studio solution that contains multiple projects. The walkthrough illustrates how to create the functional framework for a storefront Web site that has the following areas:
MvcAreasMultiProject. This is entry point to the Web application. This area includes the landing page and log in feature.
Accounts. This area is used for account management features, including billing and shipping.
Store. This area is used for product listings and reviews.
This topic contains the following sections:
A Visual Studio project with source code is available to accompany this topic: Download.
In order to complete this walkthrough, you will need:
Microsoft Visual Studio 2008 Service Pack 1 or Visual Web Developer 2008 Express Edition Service Pack 1 or a later edition of Visual Studio.
The ASP.NET MVC 2 Preview 2 framework. You can download the framework from the ASP.NET MVC 2 page on the Microsoft Download Center.
This walkthrough also assumes that you are familiar with ASP.NET MVC. For more information, see ASP.NET Model View Controller (MVC).
Creating the Application Structure
To begin, you will create a Visual Studio solution that contains three ASP.NET MVC projects—MvcAreasMultiProject (the main, or parent, project), Accounts, and Store. You will add references to the main project for each child project. You will then modify the child projects by removing unnecessary files.
To create the structure for an ASP.NET MVC area application
In Visual Studio, create a new ASP.NET MVC 2 Web Application project. Name it MvcAreasMultiProject and select the Create directory for solution check box. Do not create a unit-test project.
Without closing the solution, in the File menu, click New Project, and in the Solution menu click Add to Solution.
Name the project Accounts and click OK.
Add another project and name it Store.
In Solution Explorer, right-click the MvcAreasMultiProject project and then click Add Reference.
The Add Reference dialog box is displayed.
Click the Projects tab, select the Accounts and Store projects, and then click OK.
In the Accounts and Store projects, delete all files in the following folders (do not delete the folders themselves):
Content
Controllers
Scripts
In the Views folder of the Accounts and Store projects, delete everything (including subfolders) except the Web.config file.
In the Accounts and Store projects, delete the Global.asax file in the project root.
Now the basic structure for a Web application that supports ASP.NET MVC areas is in place. There are two types of areas—main (parent) and child. A parent area is an ASP.NET MVC Web project that contains the default style sheet, the AJAX and jQuery support scripts, and the Global.asax file for the application. The parent area acts as the entry point for the application.
A child area is an ASP.NET MVC Web project that depends on the parent for the default style sheet, basic scripts, and the Global.asax file. The parent area has a reference to each of its child areas.
Adding Content to the Accounts and Store Areas
You will now add a controller, action methods, and views to both the Accounts and Store areas.
To add content to the Accounts and Store areas
In Solution Explorer, expand the Accounts area, right-click the Controllers folder, click Add, and then click Controller.
Name the controller AccountsController and click Add.
Add a controller to the Store area, but name the controller ProjectsController.
Add the following code to the AccountsController class.
Public Class AccountsController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Return View()
End Function
Function EditBilling() As ActionResult
Return View()
End Function
Function EditShipping() As ActionResult
Return View()
End Function
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace Accounts.Controllers
{
public class AccountsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult EditBilling()
{
return View();
}
public ActionResult EditShipping()
{
return View();
}
}
}
This code creates three action methods—Index, EditBilling, and EditShipping. To keep this tutorial simple, the action methods do not contain logic to perform specific tasks.
Right-click inside each action method, click Add View, and then click Add.
In the Index view (Views\Accounts\Index.aspx), add the following code:
<p><%=Html.ActionLink("Edit Billing", "EditBilling")%></p>
<p><%=Html.ActionLink("Edit Shipping", "EditShipping")%></p>
<p><%= Html.ActionLink("Edit Billing", "EditBilling") %></p>
<p><%= Html.ActionLink("Edit Shipping", "EditShipping") %></p>
This code creates links to the EditBilling and EditShipping actions.
In the Store area, add the following code to the ProductsController class.
Public Class ProductsController
Inherits System.Web.Mvc.Controller
Function List() As ActionResult
Return View()
End Function
Function Details() As ActionResult
Return View()
End Function
Function AddReview() As ActionResult
Return View()
End Function
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace Store.Controllers
{
public class ProductsController : Controller
{
public ActionResult List()
{
return View();
}
public ActionResult Details()
{
return View();
}
public ActionResult AddReview()
{
return View();
}
}
}
This code creates three action methods—List, AddReview, and Details.
Right-click inside each action method, click Add View, and then click Add.
In the List view (Views\Products\List.aspx), add the following code:
<p><%=Html.ActionLink("Add Review", "AddReview")%></p>
<p><%=Html.ActionLink("Details", "Details")%></p>
<p><%= Html.ActionLink("Add Review", "AddReview") %></p>
<p><%= Html.ActionLink("Details", "Details") %></p>
This code creates links to the AddReview and Details actions.
Registering Routes in Accounts and Store Areas
Now you will define routes that send requests to the appropriate area, based on the request URL.
To register routes in the Accounts and Store areas
In Solution Explorer, right-click the Accounts project, click Add, and then click Class.
Name the class Routes.cs or Routes.vb and then click Add.
Add the following code to the new file:
Imports System.Web.Mvc
Public Class Routes
Inherits AreaRegistration
Public Overloads Overrides ReadOnly Property AreaName() As String
Get
Return "accounts"
End Get
End Property
Public Overloads Overrides Sub RegisterArea(ByVal context As AreaRegistrationContext)
context.MapRoute("Accounts_Default", _
"Profile/{action}/{id}", _
New With {.controller = "Accounts", .action = "Index", .id = ""} _
)
End Sub
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Accounts
{
public class Routes : AreaRegistration
{
public override string AreaName
{
get { return "Accounts"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Accounts_Default",
"Profile/{action}/{id}",
new { controller = "Accounts", action = "Index", id = "" }
);
}
}
}
This code defines the routes that map to the Accounts area.
Right-click the Store project, click Add, and then click Class.
Name the class Routes.cs or Routes.vb and then click Add.
Add the following code to the new file:
Imports System.Web.Mvc
Public Class Routes
Inherits AreaRegistration
Public Overloads Overrides ReadOnly Property AreaName() As String
Get
Return "store"
End Get
End Property
Public Overloads Overrides Sub RegisterArea(ByVal context As AreaRegistrationContext)
context.MapRoute("Store_Default", _
"Store/{controller}/{action}/{id}", _
New With {.controller = "Products", .action = "List", .id = ""} _
)
End Sub
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Store
{
public class Routes : AreaRegistration
{
public override string AreaName
{
get { return "Store"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Store_Default",
"Store/{controller}/{action}/{id}",
new { controller = "Products", action = "List", id = "" }
);
}
}
}
This code defines the routes that map to the Store area.
Adding Content to the Main Project
Next you will add code to the master view that displays diagnostic information, and you will add tabs that let users display different areas. You will also register routes for the main project.
To add content to the main project
In Solution Explorer, expand the MvcAreasMultiProject area, and then open the master view (Views\Shared\Site.Master).
Insert the following code directly after the <asp:ContentPlaceHolder ID="MainContent" runat="server" /> element.
<p>
Controller: <%=ViewContext.RouteData.Values("controller")%><br />
Action: <%=ViewContext.RouteData.Values("action")%><br />
Area: <%=ViewContext.RouteData.DataTokens("area")%>
</p>
<p>
Controller: <%= ViewContext.RouteData.Values["controller"] %><br />
Action: <%= ViewContext.RouteData.Values["action"] %><br />
Area: <%= ViewContext.RouteData.DataTokens["area"] %>
</p>
This code adds diagnostic information to the views.
In the same file, locate the <ul id="menu"> element and replace the entire ul element with the following code:
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)%></li>
<li><%= Html.ActionLink("Accounts", "Index", "Accounts", new { area = "accounts" }, null)%></li>
<li><%= Html.ActionLink("Store", "List", "Products", new { area = "store" }, null)%></li>
<li><%= Html.ActionLink("About", "About", "Home", new { area = "" }, null)%></li>
</ul>
This code adds tabs that link across areas. Links between areas are discussed in the next section in more detail.
Open the Global.asax file.
Replace the RegisterRoutes method with the following code:
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
AreaRegistration.RegisterAllAreas()
routes.MapRoute( _
"Default", _
"{controller}/{action}/{id}", _
New With {.controller = "Home", .action = "Index", .id = ""} _
)
End Sub
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
This code registers routes for the MvcAreasMultiProject area and calls the route registration methods for each child area.
Adding Area-Enabled Link to the Logon User Control
Next you will add an area-specific action to the logon user control that displays the logon and logoff links at the top of each page.
To add area-aware action links to the log on user control
In Solution Explorer, expand the MvcAreasMultiProject project and open the logon user control (Views/Shared/LogOnUserControl.ascx).
Replace the if-else statement with the following code, which contains two cross-area links.
<%
If Request.IsAuthenticated Then
%>
Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
[ <%=Html.ActionLink("Log Off", "LogOff", "Account", New With {.area = ""}, Nothing)%> ]
<%
Else
%>
[ <%=Html.ActionLink("Log On", "LogOn", "Account", New With {.area = ""}, Nothing)%> ]
<%
End If
%>
<%
if (Request.IsAuthenticated) {
%>
Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
[ <%= Html.ActionLink("Log Off", "LogOff", "Account", new { area = "" }, null)%> ]
<%
}
else {
%>
[ <%= Html.ActionLink("Log On", "LogOn", "Account", new { area = "" }, null)%> ]
<%
}
%>
This markup replaces the links in the logon user controls with area-enabled links.
Enabling the Custom Build Step for MVC Areas Projects
Now that all the code is in place, the final step is to customize the build process for each area project. This customization causes some child-area files, such as the views, to be copied to the main project before the application is built.
To enable the custom build step for MVC areas projects
In Solution Explorer, right-click each project in the solution and select Unload Project.
Right-click the Accounts project and select Edit Accounts.csproj in C# or Edit Accounts.vbproj in Visual Basic.
Locate the line that begins with the following markup:
<!-- To enable MVC area subproject support
Uncomment the two lines that follow this markup.
Locate the line that begins with the following markup:
<!-- If this is an area child project
Uncomment the line that follows this markup.
Repeat these steps and make the same changes for the Store project.
Right-click the MvcAreasMultiProject project and select Edit MvcAreasMultiProject.csproj in C# or Edit MvcAreasMultiProject.vbproj in Visual Basic.
Locate the line that begins with the following markup:
<!-- To enable MVC area subproject support
Uncomment the markup that follows this markup.
Locate the line that begins with the following markup:
<!-- If this is an area parent project
Uncomment the two lines that follow this markup.
Save each project file.
In Solution Explorer, right-click each project and then click Reload.
A warning message is displayed when Visual Studio detects that you have a custom build step in the project files. Click OK when you see this message.
Select Load Project Normally and click OK.
Right-click the MvcAreasMultiProject project and then click Set as Startup Project.
Building and Testing the Application
Now that everything is set up, you can test the application.
To build and run the application
Click CTRL-F5 to build the solution and run the application.
The default MVC template home page is displayed in the browser. The page shows the current controller (Home), the action that generated the page (Index), and the current area (Main).
Click the Accounts tab.
The Index page is displayed. The Index page contains Edit Billing and Edit Shipping links. The current controller is changed to Accounts. The action is Index, but it is the Index action in the Accounts area.
Click Edit Billing.
Notice that the controller and area remain the same, but the action is now EditBilling.
Click the Store tab.
The List page is displayed. The List page contains Add Review and Details links. The controller is now Products, the action is List, and the area is Store.
Click Log On at the top of the page.
The logon page is displayed. The controller is Accounts, the action is LogOn, and the area is Main.
Continue navigating the Web site and notice the changes to the controller, action, and area.
Other Resources