Export (0) Print
Expand All
11 out of 14 rated this helpful - Rate this topic

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.

    
    Public Class BlogController
        Inherits System.Web.Mvc.Controller
    
        Function ShowRecent() As ActionResult
            Return View()
        End Function
    
        Function ShowArchive() As ActionResult
            Return View()
        End Function
    
    End Class
    
    
    

    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.

    
    Public Class DashboardController
        Inherits System.Web.Mvc.Controller
    
        Function AddPost() As ActionResult
            Return View()
        End Function
    
        Function EditPost() As ActionResult
            Return View()
        End Function
    
    End Class
    
    
    

    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:

    
    Imports System.Web.Mvc
    
    Public Class Routes
        Inherits AreaRegistration
        Public Overloads Overrides ReadOnly Property AreaName() As String
            Get
                Return "blog"
            End Get
        End Property
    
        Public Overloads Overrides Sub RegisterArea(ByVal context As AreaRegistrationContext)
            context.MapRoute("blog_default", _
                             "blog/{controller}/{action}/{id}", _
                             New With {.controller = "Blog", .action = "ShowRecent", .id = ""} _
                             )
        End Sub
    End Class
    
    
    

    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:

    
    Imports System.Web.Mvc
    
    Public Class Routes1
        Inherits AreaRegistration
        Public Overloads Overrides ReadOnly Property AreaName() As String
            Get
                Return "dashboard"
            End Get
        End Property
    
        Public Overloads Overrides Sub RegisterArea(ByVal context As AreaRegistrationContext)
            context.MapRoute("dashboard_default", _
                             "dashboard/{controller}/{action}/{id}", _
                             New With {.controller = "Dashboard", .action = "AddPost", .id = ""} _
                             )
        End Sub
    End Class
    
    
    

    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:

    
    Public Class MvcApplication
        Inherits System.Web.HttpApplication
    
        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
    
        Sub Application_Start()
            RegisterRoutes(RouteTable.Routes)
        End Sub
    End Class
    
    
    

    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 With {.area = "blog"}, Nothing)%>

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 With {.area = ""}, Nothing)%></li>
        <li><%=Html.ActionLink("Blog", "ShowRecent", "Blog", New With {.area = "blog"}, Nothing)%></li>
        <li><%=Html.ActionLink("Dashboard", "AddPost", "Dashboard", New With {.area = "dashboard"}, Nothing)%></li>
        <li><%=Html.ActionLink("About", "About", "Home", New With {.area = ""}, Nothing)%></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.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.