tags: MVC

MVC Controller

介紹

Asp.net MVC 控制器負責控制應用程序執行的流程。 當您向 MVC 應用程序發出請求時,控制器負責將響應返回給該請求。 控制器可以執行一個或多個動作。 控制器動作可以將不同類型的動作結果返回給特定請求。 控制器負責控制應用程序邏輯,並充當視圖和模型之間的協調器。 Controller 通過 View 接收用戶的輸入,然後在 Model 的幫助下處理用戶的數據,並將結果傳遞回 View。

Create Controller

Step1. 在 Controllers 資料夾點擊滑鼠右鍵→加入→控制器

Step2. 選擇 MVC 5 控制器-空白→加入

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Step3. 輸入控制器的名稱。請記住,控制器名稱必須以控制器結尾

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

ActionResult

開啟 CustomerController.cs,在 ActionResult Index()Who() 方法內返回一段文字。

//CustomerController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC_Demo.Controllers { public class CustomerController : Controller { // GET: Customer public ActionResult Index() { return Content("This is Index action method of CustomerController"); } public ActionResult Who(int? id) //接收網址的參數,? 表示可以為 null { return Content($"ID is {id}"); } } }

在網址輸入 http://localhost/customer 或 http://localhost/customer/index,會顯示由 CustomerController 的 ActionResult Index() 方法返回的一段文字。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

在網址輸入 http://localhost/customer/who/100,會顯示由 CustomerController 的 ActionResult Who() 方法返回 ID is 100。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →