MVC中的Controller

來源:互聯網
上載者:User

標籤: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片段作為參數傳遞過來. 

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.