ASP.NET MVC - 控制器
為了學(xué)習(xí) ASP.NET MVC,我們將構(gòu)建一個 Internet 應(yīng)用程序。
第 4 部分:添加控制器。
Controllers 文件夾
Controllers 文件夾包含負(fù)責(zé)處理用戶輸入和響應(yīng)的控制類。
MVC 要求所有控制器文件的名稱以 "Controller" 結(jié)尾。
在我們的實例中,Visual Web Developer 已經(jīng)創(chuàng)建好了一下文件:HomeController.cs(用于 Home 頁面和 About 頁面)和AccountController.cs (用于登錄頁面):
Web 服務(wù)器通常會將進(jìn)入的 URL 請求直接映射到服務(wù)器上的磁盤文件。例如:URL 請求 "http://www.w3cschool.cc/index.php" 將直接映射到服務(wù)器根目錄上的文件 "index.php"。
MVC 框架的映射方式有所不同。MVC 將 URL 映射到方法。這些方法在類中被稱為"控制器"。
控制器負(fù)責(zé)處理進(jìn)入的請求,處理輸入,保存數(shù)據(jù),并把響應(yīng)發(fā)送回客戶端。
Home 控制器
在我們應(yīng)用程序中的控制器文件HomeController.cs,定義了兩個控件 Index 和 About。
把 HomeController.cs 文件的內(nèi)容替換成:
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()。