接收使用者的 Request ,經由 Url routing 後,第一關來到的是 Controller。
Controller 的責任可參考 MVC (1): Asp.NET MVC 概念說明。
Controller 的責任是:處理資料 (Model) 並挑選一個 View 回應給 Client。由 Routing ,到 Controller 處理Model,最後到 View,一氣喝成。一個關節沒弄好,就會出錯。
舉例來說,預設的 routing table 如下:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
http://localhost/Home 則會找到 HomeController 的 Index Action。請參考下例
[HandleError]
public class HomeController : Controller
{
//http://localhost:4041/Home/
public ActionResult Index()
{
return View();
}
//http://localhost:4041/About/
public ActionResult About()
{
return View();
}
//http://localhost:4041/About/3
public ActionResult About(int id)
{
ViewData["id"] = id;
return View();
}
}
如果執行 http://localhost:4041/Home的要求,但 HomeController 沒有 Index() 這個 Action的話,會出現什麼狀況呢?答案是 The resource cannot be found.
controller要如何「挑選」View 呢?答案是 View() 這個 Method
當我們使用 return View() 時,會使用同 Action 的 View。
[HandleError]
public class HomeController : Controller
{
//http://localhost:4041/Home/
public ActionResult Index()
{
return View();
//與 return View("Index") 相同
}
}
如果,硬要挑選其他名稱的 View,就要指定 View 的名稱。如下例
[HandleError]
public class HomeController : Controller
{
//http://localhost:4041/Home/
public ActionResult Index()
{
return View("List"); //雖然是 HomeController下的 Index Action,但指名挑選名為 List 的 View
}
}
沒有留言:
張貼留言