
ASP.NET MVC Framework - Controller

MVC:Model-View-Controller 軟體設計模式
其中包含以下三大面向:
- Controller:從 Model 拿資料再將其提供給 View
View用:呈現使者看到的畫面
Model:處理商業邏輯,提供資料
MVC Project Build
使用 Visual Studio 2019 開新專案,選擇 ASP.NET Web Application (.NET Framework) Visual C# 範本

一般使用可選擇空白範本,並勾選 MVC 加入資料夾和核心參考即可

Controller
一個系統可以有多個 Controller
例如:LoginController、HomeController、OrderController…
Controller Build
建置方式:
在專案的方案總管中 Controller 的資料夾上按右鍵選擇 加入 -> 控制器 -> MVC5 控制器 - 空白

在新增 Controller 需取名,預設為 DefaultController
注意!!
Controller 取名時僅可更動前綴名稱,勿改動 Controller 結尾!!!千萬不可以拿掉
ex 可將 DefaultController 更名為 TestController
因為 MVC Routing 規則預設為 url: "{controller}/{action}/{id}"
所以 MVC 會自動判斷 controller 名稱導入 routing 路徑
ActionResult
一個 Controller 裡可以有多個 Action
例如:OrderController 裡可能有 Index Action、InsertOrder Action、UperdateOrder Action、DeleteOrder Action..
也就是一個 Controller 下會有多個 ActionResult,控制不同 function 的回傳,最常見為 return View()
例如網頁預設路徑於 Index,即會撰寫如下
1 | public class DefaultController : Controller |
順帶一提,可在 C# 裡寫包含 XML 標記的註解,快捷鍵是在 ActionResult 前打
///
HttpPost ActionResult
若希望讓 ActionResult 吃到以 Post 方式回傳的資料,可在 ActionResult 前加上 [HttpPost()]
1 | public class DefaultController : Controller |
JsonResult
關於 JSON 的一些小知識:ASP.NET MVC Framework - JSON