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

MVC2: Adding ASP.NET AJAX Scripting to an MVC Project

本文主要應用 System.Web.Mvc.AjaxHelper 物件, 進行ajax的應用開發;請確定你有VS2010(預設就是MVC2),本主參考自 http://msdn.microsoft.com/en-us/library/dd381533(v=vs.100).aspx?cs-save-lang=1
但是我找到這個練習的完整程式碼,所以自己實作了一個,並附件在文章後.

ASP.NET AJAX enables a Web application to retrieve data from the server asynchronously and to update parts of the existing page. This improves the user experience by making the Web application more responsive.
This walkthrough shows how to get started with adding ASP.NET AJAX functionality to an ASP.NET MVC application.
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. You cannot use Microsoft Visual Web Developer Express for this walkthrough.
  • 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.


To begin, you will create a new ASP.NET MVC project. To keep this walkthrough simple, you will not create the test project that is an option for ASP.NET MVC projects. For more information about how to create an MVC test project, see Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio.
To create a new MVC project
  1. On the File menu, click New Project.
  2. In the New Project dialog box under Project types, expand either Visual Basic or Visual C#, and then clickWeb.
  3. Under Visual Studio installed templates, select ASP.NET MVC Web Application.
  4. In the Name box, type MvcAjaxApplication.
  5. In the Location box, enter the name of the project folder.
  6. Select Create directory for solution.
  7. Click OK.
  8. In the Create Test Project dialog box, select No, do not create a unit test project.
NoteNote
If you are using the Visual Studio 2008 Standard, the Create Unit Test Project dialog box is not displayed. Instead, the new MVC application project is generated without a test project.
  1. Click OK.
The new MVC application project is generated.


Support for the client functionality of ASP.NET AJAX is in two script libraries: MicrosoftAjax.js and MicrosoftMvcAjax.js. The release version and the debug version of these scripts are located in the project's Scripts folder. Before you can access these libraries in client script, you must add library references to the MVC views in the current project.
To reference the ASP.NET AJAX script libraries
  1. In Solution Explorer, expand the Views folder, and then expand the Shared folder.
  2. Double-click the Site.Master file to open it.
  3. Add the following markup at the end of the head element:
C# & VB
    <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>"
           type="text/javascript"></script> 
    <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
           type="text/javascript"></script>

Alternatively, you can drag these files from Solution Explorer onto the Site.Master view, and this code will be added for you.


Next you will add two action methods that can be called asynchronously from client script. The GetStatus method just returns a status of "OK" and the current time. The UpdateForm method receives input from an HTML form and returns a message that includes the current time.
To add the action methods to the HomeController class
  1. In Solution Explorer, expand the Controllers folder, and then double-click the HomeController class to open it.
  2. Add the following code after the About method.
C#
public string GetStatus()
{
    return "Status OK at " + DateTime.Now.ToLongTimeString();
}

public string UpdateForm(string textBox1)
{
    if (textBox1 != "Enter text")
    {
        return "You entered: \"" + textBox1.ToString() + "\" at " +
            DateTime.Now.ToLongTimeString();
    }

    return String.Empty;
}
Public Function GetStatus() As String
    Return "Status OK at " + DateTime.Now.ToLongTimeString()
End Function

Public Function UpdateForm(ByVal textBox1 As String) As String
    If textBox1 <> "Enter text" Then
        Return "You entered: """ + textBox1.ToString() + """ at " + DateTime.Now.ToLongTimeString()
    End If

    Return [String].Empty
End Function



Finally, you will replace the content of the Index.aspx page, which is added automatically to the Visual Studio project for ASP.NET MVC. The new Index.aspx page displays the time that the page is rendered, a status message that has a link for updating the message asynchronously, and a form for submitting a text string.
To redefine the Index page
  1. In Solution Explorer, expand the Views folder, expand the Home folder, and then open the Index view.
  2. Replace the content of the Content control with the following markup:
C#
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
    Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
</p>
<span id="status">No Status</span>
<br />  
<%= Ajax.ActionLink("Update Status", "GetStatus", new AjaxOptions{UpdateTargetId="status" }) %>
<br /><br />
<% using(Ajax.BeginForm("UpdateForm", new AjaxOptions{UpdateTargetId="textEntered"})) { %>
  <%= Html.TextBox("textBox1","Enter text")%> 
  <input type="submit" value="Submit"/><br />
  <span id="textEntered">Nothing Entered</span>
<% } %>
// Ajax.ActionLink是建立一個連結呼叫controll內的function
// Ajax.BeginForm
是建立一個<form>開頭的標簽
<h2><%= Html.Encode(ViewData("Message")) %></h2>
<p>
  Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
</p>
<span id="status">No Status</span>
<br />  
<%=Ajax.ActionLink("Update Status", "GetStatus", New AjaxOptions With {.UpdateTargetId = "status"})%>
<br /><br />
<% Using (Ajax.BeginForm("UpdateForm", New AjaxOptions With {.UpdateTargetId = "textEntered"}))%>
  <%= Html.TextBox("textBox1","Enter text")%> 
  <input type="submit" value="Submit"/>
  <br />
  <span id="textEntered">Nothing Entered</span>
<% End Using%>

In the example, an asynchronous link is created by calling the Ajax.ActionLink method. This method has several overrides. In this example, it accepts three parameters. The first parameter is the text for the link. The second parameter is the MVC action method to call. The third parameter is an AjaxOptions object that defines the intended purpose of the call. In this case, the code will update the DOM element whose ID isstatus.
The form is defined by using the Ajax.Form method, which also has several overrides. In this example, it accepts two parameters. The first parameter is the action method to call. The second parameter is anotherAjaxOptions object, which specifies that the DOM element whose ID is textEntered is to be updated.


Now you can run the application and see how it works.
To run the MVC application
  1. Press CTRL+F5.
The page displays the time that it was rendered.
  1. Click the Update Status link.
The status message is updated with the time that it was updated. Notice that only the status message was updated.
  1. Enter text in the text box and then click the Submit button.
A message displays the text that you entered and the time it was entered. Once again, notice that only the form was processed.


Tasks
Other Resources