Export (0) Print
Expand All

Walkthrough: Creating an ASP.NET MVC Areas Application Using Multiple Projects

[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).

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

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

  2. Without closing the solution, in the File menu, click New Project, and in the Solution menu click Add to Solution.

  3. Name the project Accounts and click OK.

  4. Add another project and name it Store.

  5. In Solution Explorer, right-click the MvcAreasMultiProject project and then click Add Reference.

    The Add Reference dialog box is displayed.

  6. Click the Projects tab, select the Accounts and Store projects, and then click OK.

  7. In the Accounts and Store projects, delete all files in the following folders (do not delete the folders themselves):

    • Content

    • Controllers

    • Scripts

  8. In the Views folder of the Accounts and Store projects, delete everything (including subfolders) except the Web.config file.

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

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

  1. In Solution Explorer, expand the Accounts area, right-click the Controllers folder, click Add, and then click Controller.

  2. Name the controller AccountsController and click Add.

  3. Add a controller to the Store area, but name the controller ProjectsController.

  4. Add the following code to the AccountsController 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.

  5. Right-click inside each action method, click Add View, and then click Add.

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

    This code creates links to the EditBilling and EditShipping actions.

  7. In the Store area, add the following code to the ProductsController 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.

  8. Right-click inside each action method, click Add View, and then click Add.

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

    This code creates links to the AddReview and Details actions.

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

  1. In Solution Explorer, right-click the Accounts project, click Add, and then click Class.

  2. Name the class Routes.cs or Routes.vb and then click Add.

  3. Add the following code to the new file:

    
    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.

  4. Right-click the Store project, click Add, and then click Class.

  5. Name the class Routes.cs or Routes.vb and then click Add.

  6. Add the following code to the new file:

    
    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.

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

  1. In Solution Explorer, expand the MvcAreasMultiProject area, and then open the master view (Views\Shared\Site.Master).

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

    This code adds diagnostic information to the views.

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

  4. Open the Global.asax file.

  5. Replace the RegisterRoutes method with the following code:

    
    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.

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

  1. In Solution Explorer, expand the MvcAreasMultiProject project and open the logon user control (Views/Shared/LogOnUserControl.ascx).

  2. Replace the if-else statement with the following code, which contains two cross-area links.

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

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

  1. In Solution Explorer, right-click each project in the solution and select Unload Project.

  2. Right-click the Accounts project and select Edit Accounts.csproj in C# or Edit Accounts.vbproj in Visual Basic.

  3. Locate the line that begins with the following markup:

    <!-- To enable MVC area subproject support
    
    
  4. Uncomment the two lines that follow this markup.

  5. Locate the line that begins with the following markup:

    <!-- If this is an area child project
    
    
  6. Uncomment the line that follows this markup.

  7. Repeat these steps and make the same changes for the Store project.

  8. Right-click the MvcAreasMultiProject project and select Edit MvcAreasMultiProject.csproj in C# or Edit MvcAreasMultiProject.vbproj in Visual Basic.

  9. Locate the line that begins with the following markup:

    <!-- To enable MVC area subproject support
    
    
  10. Uncomment the markup that follows this markup.

  11. Locate the line that begins with the following markup:

    <!-- If this is an area parent project
    
    
  12. Uncomment the two lines that follow this markup.

  13. Save each project file.

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

  15. Select Load Project Normally and click OK.

  16. Right-click the MvcAreasMultiProject project and then click Set as Startup Project.

Now that everything is set up, you can test the application.

To build and run the application

  1. 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).

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

  3. Click Edit Billing.

    Notice that the controller and area remain the same, but the action is now EditBilling.

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

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

  6. Continue navigating the Web site and notice the changes to the controller, action, and area.

Show:
© 2014 Microsoft