標籤:des style blog http color java io strong
Controller是MVC模式中的三個核心元素之一.
MVC模式中的Controller主要負責響應使用者的輸入, 並在響應時修改Model.
MVC提供的是方法調用的結果, 而不是動態產生的頁面.
下面建立一個項目名為 MVC Music Store , 以此為例說明一下MVC中的Controller.
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace MvcMusicStore.Controllers 8 { 9 public class HomeController : Controller10 {11 12 public ActionResult Index()13 {
// 將預設內容修改為"I like cake!" 後即可直接顯示在首頁上. 14 ViewBag.Message = "I like cake!";15 return View();16 }17 18 public ActionResult About()19 {20 ViewBag.Message = "Your app description page.";21 22 return View();23 }24 25 public ActionResult Contact()26 {27 ViewBag.Message = "Your contact page.";28 29 return View();30 }31 }32 }
HomeController 類的Index方法負責決定當瀏覽網站首頁時觸發的事件.
下面建立一個新的控制器並命名為 StoreController, 作如下修改:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcMusicStore.Controllers{ public class StoreController : Controller { // // GET: /Store/ public string Index() { return "Hello from Store.Index()"; } //get: /Store/Browse public string Browse(string genre) { return "Hello from Store.Browse() "; } public string Details() { return "Hello from Store.Details()"; } }}
不需要額外配置,瀏覽到/Store/Details就可以執行StoreController類中的Details方法,這就是操作中的路由.
判斷一個類是否是Controller的唯一方式,就是看該類是否繼承自System.Web.Mvc.Controller.
Controoller 才是MVC中真正的核心, 每一個請求都必須通過控制器處理. 有些請求是不需要Model和View的.
public string Browse(string genre) { string message = HttpUtility.HtmlEncode("Store.Browse, Genre= " + genre); return message; }
利用HttpUtility.HtmlEncode來預先處理使用者輸入. 這樣就能阻止使用者用連結向視圖中注入JavaScript代碼或HTML標記.
控制器可將查詢字串作為其操作方法的參數來接受.
ASP.NET MVC 的預設路由約定,就是將操作方法名稱後面URL的這個片段作為一個參數, 該參數的名稱為ID. 如果操作方法中有名為ID的參數, 那麼ASP.NET MVC 會自動將這個URL片段作為參數傳遞過來.