2013年8月1日 星期四

Organizing an ASP.NET MVC Application using Areas

The MVC pattern separates the model (data) logic of an application from its presentation logic and business logic. In ASP.NET MVC, this logical separation is also implemented physically in the project structure, where controllers and views are kept in folders that use naming conventions to define relationships. This structure supports the needs of most Web applications.
However, some applications can have a large number of controllers, and each controller can be associated with several views. For these types of applications, the default ASP.NET MVC project structure can become unwieldy.
To accommodate large projects, ASP.NET MVC lets you partition Web applications into smaller units that are referred to as areas. Areas provide a way to separate a large MVC Web application into smaller functional groupings. An area is effectively an MVC structure inside an application. An application could contain several MVC structures (areas).
For example, a single large e-commerce application might be divided into areas that represent the storefront, product reviews, user account administration, and the purchasing system. Each area represents a separate function of the overall application.
This walkthrough demonstrates how to implement areas in an ASP.NET MVC application. The walkthrough creates the functional framework for a 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 to display blog posts and to search the archive.
  • Dashboard. This area is used to create and edit blog posts.
To keep this tutorial simple, the areas do not contain logic to perform the actual tasks for the blog.
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 version.
  • The ASP.NET MVC 2 framework. If you have installed Visual Studio 2010, the ASP.NET MVC 2 is already installed on your computer. To download the most up-to-date version of the framework, see the ASP.NET MVC download page.
This walkthrough assumes that you are familiar with ASP.NET MVC. For more information, see ASP.NET MVC 2.

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, in the File menu, and click New Project.
  2. In the Project types window, expand the Visual Basic node or the Visual C# node, and then select theWeb node.
  3. In the Templates window, select ASP.NET MVC 2 Web Application.
  4. Name the project MvcAreasApplication, set the project location, and then select the Create directory for solution check box.
  5. Click OK.
  6. In Solution Explorer, right-click the project name, click Add, and then click Area.
  7. In Area Name, type Blog and then click Add.
An Areas folder is added to the project. The Areas folder contains a folder structure that allows each child area to have its own models, views, and controllers.
  1. In Solution Explorer, right-click the project name, click Add, and then click Area.
  2. In Area Name, enter Dashboard and then click Add.
When you are done, the Areas folder contains two child areas, Blog and Dashboard.

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 clickController.
  2. Name the controller BlogController and then click Add.
  3. Add the following code to the BlogController class.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcAreasApplication.Areas.Blog.Controllers
{
    public class BlogController : Controller
    {
        public ActionResult ShowRecent()
        {
            return View();
        }

        public ActionResult ShowArchive()
        {
            return View();
        }
    }
}


This code creates two action methods named ShowRecent and ShowArchive. To keep this tutorial simple, the action methods do not contain logic to perform specific tasks.
  1. In the Dashboard area, right-click the Controllers subfolder, click Add, and then click Controller.
  2. Name the controller DashboardController and click Add.
  3. Add the following code to the DashboardController class.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcAreasApplication.Areas.Dashboard.Controllers
{
    public class DashboardController : Controller
    {
        public ActionResult AddPost()
        {
            return View();
        }

        public ActionResult EditPost()
        {
            return View();
        }
    }
}

This code creates two action methods named 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.
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.
  1. Right-click inside the ShowArchive method, click Add View, and then click Add.
  2. In the ShowArchive view, add the following markup to the page content after the header:
<p><%= Html.ActionLink("Show Recent", "ShowRecent") %></p>
  1. Open the DashboardController class, right-click inside the AddPost action method, click Add View, and then click Add.
  2. In the AddPost view, add the following markup to the page content after the header:
<p><%= Html.ActionLink("Edit Post", "EditPost") %></p>
  1. Right-click inside the EditPost method, click Add View, and then click Add.
  2. In the EditPost view, add the following markup to the page content after the header:
<p><%= Html.ActionLink("Add Post", "AddPost") %></p>

When you add an area to a project, a route for the area is defined in an AreaRegistration file. The route sends requests to the area based on the request URL. To register routes for areas, you add code to the Global.asax file that can automatically find the area routes in the AreaRegistration file.
(jk:這段是說每一個Area都會有一個AreaRegistration.cs的檔案(會有一個AreaRegistration的類別),會註冊路由…)
To register area routes
  1. In Solution Explorer, open the Global.asax file for the project.
  2. Insert the following code into the Application_Start method:
C#
AreaRegistration.RegisterAllAreas();
VB
AreaRegistration.RegisterAllAreas()
This code calls the route registration methods for each child area.

In an ASP.NET MVC area application, you can link within an area as you would in any MVC application. For example, you can call the ActionLink method, or you can call any other routine that takes a controller or action name (such as the RedirectToAction method).
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. This call does not identify a specific area.
<%= Html.ActionLink("Show Blog", "ShowBlog", "Blog") %>
The link will work as expected anywhere within the Blog area(Blogarea內是正確的). However, if the preceding link is added to a view in the Dashboard area, it will fail. This is because the ASP.NET MVC framework would not be able to find the BlogController class in the Dashboard area.
The following example shows how to create a link that identifies the area in an anonymous object passed in the routeValues  parameter. This example is shown only as an explanation. Do not add it to your project.
(jk: Html.ActionLink共有10Overload主要是要給linkText actionName)
(jk: 如果要產生不同area的連結,就一定要給目地的area名稱在routeValues的參數內)
C#
<%= 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.
Adding Content to the Main Project
When you created the Visual Studio solution for this walkthrough, the solution template included a master view that acts as the 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.
C#
<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.
  1. In the same file, find the <ul id="menu"> element and replace the whole element with the following code:
C#
<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.
  1. 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.
  1. Click Show Archive.
Notice that the controller and area remain the same, but the action is now ShowArchive.
  1. 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.
  1. Continue navigating the Web site and notice the changes to the controller, action, and area.

Other Resources

沒有留言: