Export (0) Print
Expand All

Walkthrough: Creating an ASP.NET MVC Areas Application Using a Single Project

[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 a single project. The walkthrough creates the functional framework for a weblog (blog) site that has the following areas:

  • Main. This is entry point to the Web application. This area includes the landing page and a log-in feature.

  • Blog. This area is used for displaying blog posts and searching the archive.

  • Dashboard. This area is used for creating and editing blog posts.

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 release 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 an ASP.NET MVC project and add the folder structure for two child areas (Blog and Dashboard).

To create the application structure

  1. In Visual Studio, create a new ASP.NET MVC 2 Web Application project. Name it MvcAreasSingleProject and select the Create directory for solution check box. Do not create a unit-test project.

  2. In Solution Explorer, right-click the project name, click Add, and then click New Folder.

  3. Name the folder Areas.

  4. Right-click the Areas folder and add two folders named Blog and Dashboard.

  5. In the Blog and Dashboard folders, create a subfolder named Controllers.

    The finished areas folder will have the following structure:

    Areas

        Blog

            Controllers

        Dashboard

             Controllers

You will now add area-enabled controllers and action methods for each area.

To add area controllers

  1. In Solution Explorer, right-click the Controllers subfolder for the Blog area, click Add, and then click Controller.

  2. Name the controller BlogController and then click Add.

  3. Add the following code to the BlogController class.

    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    
    namespace MvcAreasSingleProject.Areas.Blog.Controllers
    {
        public class BlogController : Controller
        {
            public ActionResult ShowRecent()
            {
                return View();
            }
    
            public ActionResult ShowArchive()
            {
                return View();
            }
        }
    }
    
    
    

    This code creates two action methods—ShowRecent and ShowArchive. To keep this tutorial simple, the action methods do not contain logic to perform specific tasks.

  4. In the Dashboard area, right-click the Controllers subfolder, click Add, and then click Controller.

  5. Name the controller DashboardController and click Add.

  6. Add the following code to the DashboardController class.

    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    
    namespace MvcAreasSingleProject.Areas.Dashboard.Controllers
    {
        public class DashboardController : Controller
        {
            public ActionResult AddPost()
            {
                return View();
            }
    
            public ActionResult EditPost()
            {
                return View();
            }
        }
    }
    
    
    

    This code creates two action methods—AddPost and EditPost. To keep this tutorial simple, the action methods do not contain logic to perform specific tasks.

Next you will add area-enabled views for each action method. The views for each area require their own copy of the Web.config file, so you will copy the file into each area.

To add area views

  1. Open the BlogController class, right-click inside the ShowRecent action method, click Add View, and then click Add.

  2. In the ShowRecent view, add the following markup to the page content after the header:

    <p><%= Html.ActionLink("Show Archive", "ShowArchive") %></p>
    
    

    This markup creates a link to the ShowArchive action method that you created earlier.

  3. Right-click inside the ShowArchive method, click Add View, and then click Add.

  4. In the ShowArchive view, add the following markup to the page content after the header:

    <p><%= Html.ActionLink("Show Recent", "ShowRecent") %></p>
    
    
  5. In the Blog area, right-click the Views folder, click Add, and then click Existing Item.

    The Add Existing Item dialog box is displayed.

  6. In the dialog box, browse to the Views folder of the main project, select the Web.config file, and then click Add.

    This copies the Web.config file to the Blog area.

  7. Open the DashboardController class, right-click inside the AddPost action method, click Add View, and then click Add.

  8. In the AddPost view, add the following markup to the page content after the header:

    <p><%= Html.ActionLink("Edit Post", "EditPost") %></p>
    
    
  9. Right-click inside the EditPost method, click Add View, and then click Add.

  10. In the EditPost view, add the following markup to the page content after the header:

    <p><%= Html.ActionLink("Add Post", "AddPost") %></p>
    
    
  11. Right-click the Views folder under the Dashboard area, click Add, and then click Existing Item.

    The Add Existing Item dialog box is displayed.

  12. In the dialog box, select the Web.config file and then click Add.

    This copies the Web.config file to the Dashboard area.

When you create an ASP.NET MVC application that includes areas, you must define routes that send requests to the appropriate area based on the request URL. To register a route that can respond to area-specific requests, you add a Routes class to the area. Your Routes class inherits from the AreaRegistration class. You can name an area by overriding the AreaName property and set up routes for the area by overriding the RegisterArea method.

By calling the RegisterAllAreas method from the Global.asax file, you cause the framework to find and use your Routes class to register routes for the area.

To register area routes

  1. In Solution Explorer, right-click the Blog folder, 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 MvcAreasSingleProject.Areas.Blog
    {
        public class Routes : AreaRegistration
        {
            public override string AreaName
            {
                get { return "blog"; }
            }
    
            public override void RegisterArea(AreaRegistrationContext context)
            {
                context.MapRoute(
                    "blog_default",
                    "blog/{controller}/{action}/{id}",
                    new { controller = "Blog", action = "ShowRecent", id = "" }
                );
            }
        }
    }
    
    
    

    This code defines the routes that map to the Blog area.

  4. Right-click the Dashboard folder, 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 MvcAreasSingleProject.Areas.Dashboard
    {
        public class Routes : AreaRegistration
        {
            public override string AreaName
            {
                get { return "dashboard"; }
            }
    
            public override void RegisterArea(AreaRegistrationContext context)
            {
                context.MapRoute(
                    "dashboard_default",
                    "dashboard/{controller}/{action}/{id}",
                    new { controller = "Dashboard", action = "AddPost", id = "" }
                );
            }
        }
    }
    
    
    

    This code defines the routes that map to the Dashboard area.

  7. Open the Global.asax file.

  8. Replace the RegisterRoutes method with the following code:

    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace MvcAreasSingleProject
    {
        // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
        // visit http://go.microsoft.com/?LinkId=9394801
    
        public class MvcApplication : System.Web.HttpApplication
        {
            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
                );
    
            }
    
            protected void Application_Start()
            {
                RegisterRoutes(RouteTable.Routes);
            }
        }
    }
    
    
    

    This code registers routes for the main area and calls the route registration methods for each child area.

In an ASP.NET MVC area application, linking within an area by using the ActionLink method or by using any other routine that takes a controller or action name (such as the RedirectToAction method) works the same as in a standard MVC application. However, to generate a link to a different area, you must explicitly pass the target area name in the routeValues parameter for these methods.

For example, the following markup shows a link to the ShowBlog action method of BlogController class that does not identify the area.

<%= Html.ActionLink("Show Blog", "ShowBlog", "Blog") %>

The link will work as expected anywhere within the Blog area. However, if the preceding link is added to a view in the Dashboard area, it will fail, because the ASP.NET MVC framework would not be able to find the BlogController class in the Dashboard area.

The following link identifies the area in an anonymous object passed in the routeValues parameter.

<%= Html.ActionLink("Show Blog", "ShowBlog", "Blog", new { area = "blog" }, null) %>

NoteNote

The last null parameter (Nothing in Visual Basic) is required only because the ActionLink method overloads that have a routeValues parameter also have an htmlAttributes parameter. However, this parameter is not required in order to be able to link between areas.

When you created the Visual Studio solution for this walkthrough, the solution template included a master view that acts as the main entry point for the application. In this section of the walkthrough, you will add tabs to the master view that link to the child areas. You will also add code to display diagnostic information, including the name of the controller, action method, and area that produced the current view.

To add content to the main project

  1. 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 element with the following code:

    
    <ul id="menu">              
        <li><%= Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)%></li>
        <li><%= Html.ActionLink("Blog", "ShowRecent", "Blog", new { area = "blog" }, null)%></li>
        <li><%= Html.ActionLink("Dashboard", "AddPost", "Dashboard", new { area = "dashboard" }, null)%></li>
        <li><%= Html.ActionLink("About", "About", "Home", new { area = "" }, null)%></li>
    </ul>
    
    
    

    This code adds tabs that link across areas.

Now you can build and 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, which is blank and which indicates the main area.

  2. Click the Blog tab.

    The ShowBlog page is displayed. The ShowBlog page contains a link to the ShowArchive page. The current controller is changed to Blog. The action is ShowBlog, and the area is blog.

  3. Click Show Archive.

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

  4. Click the Dashboard tab.

    The AddPost page is displayed. The AddPost page contains a link to the EditPost page. The controller is now Dashboard, the action is AddPost, and the area is dashboard.

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

Show:
© 2014 Microsoft