Share via


Exercise 4: ASP.NET MVC Areas

In this exercise, you will learn how to use ASP.NET MVC Areas, taking advantage of the new tooling in ASP.NET MVC 2 for VS2010, which includes templates and context menu items (for example, Add Area item template). Moreover you will see how to register the routes of the area you have created.

MVC Areas were designed to provide a way for partitioning your application into areas of functionality. This helps building and managing large applications.

The exercise starts with an all-in-one solution, which simulates a large web application, and guides you through the process of extracting the logon functionality to a new area.

Task 1 – Creating the New Account Area

  1. Open Microsoft Visual Studio 2010. Click Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.
  2. Open the solution file Begin.sln located under \Ex4-MVCAreas\begin\ (Choosing the folder that matches the language of your preference). Alternatively, you can continue working with the solution obtained after completing exercise 3.
  3. You will take advantage of the item template provided by MVC 2 to create an area which will contain assets required for managing an account; to do this, right-click the PlanMyNight project and select Add | Area...
  4. Set the Area Name to Account in the Add Area dialog, and click OK

    A new Areas folder will be created, containing the Account subfolder inside.

    Figure 40

    Solution structure after create the Account Area (C#)

    Figure 41

    Solution structure after create the Account Area (Visual Basic)

    A folder for each area is created inside the Areas folder of the MVC project when you use the New Area item template. Each area folder has a similar structure than your main project, Controllers, Models and Views folder can be found within them.

    The AccountAreaRegistration.cs (C#) or AccountAreaRegistration.vb (Visual Basic) file is also created inside the new area folder. This file contains the area-specific route definition.

Task 2 – Moving the Account Controller and Views from the Main Project to the new Area

In this task, you will move the assets needed for managing account to the new Account area.

  1. Drag the AccountController.cs (C#) or AccountController.vb (Visual Basic) file, located inside the root’s Controllers folder, and drop it inside Areas/Account/Controllers.
  2. Proceed as before, but now drag the Account folder instead, located inside the root’s Views folder, and drop it inside Areas/Account/Views.
  3. After completing the previous steps, your solution structure should look like the following:

    Figure 42

    Solution structure after move security assets to the new Account area (C#)

    Figure 43

    Solution structure after move security assets to the new Account area (Visual Basic)

Task 3 – Registering Account Routes

Up to this point, you have moved the required assets to the corresponding area folder. In order for the main project to be aware of the Account Area, you need to register the corresponding routes in the root’s RouteCollection.

To do this, you will invoke the AreaRegistration.RegisterAllAreas() method from within the project’s Global.asax file.

Note:
The new MVC 2 Project Templates already include the invocation to this method within the global.asax file.

  1. In the Solution Explorer double-click on the Global.asax file, located in PlanMyNight’s root directory, to open it.
  2. Add an invocation to RegisterAllAreas inside RegisterRoutes as it is shown below: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
    );
    }

    Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

    AreaRegistration.RegisterAllAreas()

    ' MapRoute takes the following parameters, in order:
    ' (1) Route name
    ' (2) URL with parameters
    ' (3) Parameter defaults
    routes.MapRoute( _
    "Default", _
    "{controller}/{action}/{id}", _
    New With {.controller = "Home", .action = "Index", .id = ""} _
    )
    End Sub

    Note:
    method searches for the different areas on your project, and executes the RegisterArea method of each of them (you can find this method inside the AreaRegistration class created automatically by the Areas Template.)

    Within the AreaRegistration class, you should add the code to register all the routes required by your application.

Task 4 – Modifying the Code to Navigate Between the Main and Account Area

Finally, you will update the navigation links to target the correct area.

  1. In the solution explorer, Double-click on the Site.Master file, located inside Views\Shared, to open it.
  2. Update the Html.ActionLink declaration inside the <div> with “navigation” id, to define if the action is located in a specific area (“account”) or on the root project ( “” ).<div id="navigation">
    <ul>
    <li><%=Html.ActionLink("Search", "Index", "Home", new { area = "" }, null)%></li>
    <li><%=Html.ActionLink("Create", "Create", "Activities", new { area = "" }, null)%></li>
    <li><a href="#">About</a></li>
    <%
    if (Request.IsAuthenticated) {
    %>
    <li><%=Html.ActionLink("Log Off", "LogOff", "Account", new { area = "account" }, null)%></li>
    <%
    } else {
    %>
    <li><%=Html.ActionLink("Log On", "LogOn", "Account", new { area = "account" }, null)%></li>
    <%
    }
    %>
    </ul>
    </div>

    <div id="navigation">
    <ul>
    <li><%= Html.ActionLink("Search", "Index", "Home",New With {.area = ""}, Nothing)%></li>
    <li><%= Html.ActionLink("Create", "Create", "Activities", New With {.area = ""}, Nothing)%></li>
    <li><a href="#">About</a></li>
    <%
    If (Request.IsAuthenticated) Then
    %>
    <li><%= Html.ActionLink("Log Off", "LogOff", "Account",New With {.area = "account"}, Nothing)%></li>
    <%
    Else
    %>
    <li><%= Html.ActionLink("Log On", "LogOn", "Account",New With {.area = "account"}, Nothing)%></li>
    <%
    End If
    %>
    </ul>
    </div>

    Note:
    The fourth parameter defines the routeValues for the action link; while the fifth is the HtmlAttributes parameter and is not required.

    Note:
    Since the Master Page will be used throughout the application, you need to explicitly tell in which area the target page should be found.

    That is why you add the routeValue area = “” on those links that point to the pages located in the main project.

  3. Additionally, you need to change the RedirectToAction declaration inside the AccountController to point to the main area, since they are invoking the actions on the HomeController. To do this, open the AccountController.cs (C#) or AccountController.vb (VB) file, located inside the Areas\Account\Controllers folder.
  4. Update the 3 RedirectToAction invocations, to include the routeValue specifying the main area.

    The updated code should look as follows:

    return RedirectToAction("Index", "Home", new { area = "" });

    Return RedirectToAction("Index", "Home", New With {.area = ""})

    Note:
    RedirectToAction invocations can be found on the following 3 methods of the AccountController:

    - LogOn(string, string, bool, string)

    - LogOff()

    - Register(string, string, string, string)

  5. If you run the solution now, the Account controller inside the new area will not be found because MVC will be search for it inside the PlanMyNight.Areas.Account.Controllers namespace. Since you have moved the controller from the root project, Update the Account Controller’s namespace to match the following:namespace PlanMyNight.Areas.Account.Controllers
    {

    [HandleError]
    public class AccountController : Controller
    {
    ...
    }
    }

    Namespace PlanMyNight.Areas.Account.Controllers
    <HandleError()> _
    Public Class AccountController
    Inherits System.Web.Mvc.Controller
    ...
    End Class
    End Namespace

Exercise 4: Verification

  1. Press CTRL+F5 to run the solution without debugging.
  2. Hover the mouse pointer over the links in the navigation bar. Notice that the first two links point to actions inside controllers of the MVC project, while LOG ON point to the LogOn action available on the Account controller of the Account area.

    Figure 44

    PlanMyNight’s Search page pointing to the LOG ON link

    Note:
    About is a placeholder only; that is why it links to self (#.)

  3. Click the LOG ON link at the top of the page.
  4. Click the Register link to create a new user.
  5. Fill the Account Information form with some valid data and click Register.

    Figure 45

    Registering a user in PlanMyNight

  6. You should be redirected to the PlanMyNight’s Search page where the LOG ON link change for LOG OFF. It points to the LogOff action available in the Account controller of the Account Area.

    Figure 46

    PlanMyNight’s Search page pointing to the LOG OFF link