Latest web development tutorials

ASP.NET MVC 控制器

為了學習ASP.NET MVC,我們將構建一個Internet 應用程序。

第4 部分:添加控制器。


Controllers 文件夾

Controllers文件夾包含負責處理用戶輸入和響應的控制類。

MVC 要求所有控制器文件的名稱以"Controller" 結尾。

在我們的實例中,Visual Web Developer已經創建好了一下文件: HomeController.cs (用於Home頁面和About頁面)和AccountController.cs (用於登錄頁面):

Controllers

Web 服務器通常會將進入的URL 請求直接映射到服務器上的磁盤文件。 例如:URL 請求"http://www.w3cschool.cc/index.php" 將直接映射到服務器根目錄上的文件"index.php"。

MVC 框架的映射方式有所不同。 MVC 將URL 映射到方法。 這些方法在類中被稱為"控制器"。

控制器負責處理進入的請求,處理輸入,保存數據,並把響應發送回客戶端。


Home 控制器

在我們應用程序中的控制器文件HomeController.cs ,定義了兩個控件IndexAbout

把HomeController.cs 文件的內容替換成:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{return View();}

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


Controller 視圖

Views文件夾中的文件Index.cshtmlAbout.cshtml定義了控制器中的ActionResult視圖Index()和About()。