這節我們讓ASP.NET MVC真正的跑起來
一、建立Controller
首先我們自己建立一個新的Controller在Controllers上點右鍵,添加,Controller選項
之後出現一個對話方塊:
這裡我們將之起名為EiceController
附註一下,這裡是個純廣告,沒有興趣可略過此行:www.eice.com.cn為您建立Web2.0社交網站
預設產生的程式碼如下:
//記不記得前面講過的,所有Controller都要繼承於Controller類 public class EiceController : Controller { public ActionResult Index() { return View(); } }二、建立View檔案
當然,除了Controller我們還要建個View,先在Views中建個Eice檔案夾,然後我們要在其中建個Index.aspx。
不過除此之外ASP.NET MVC還為我們提供了一種建立View的捷徑。
在對應的Controller的Action中點右鍵,選擇Add View。
之後快顯視窗
確定好View檔案名稱字及母片檔案後點Add就建好了一個View檔案。
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Index</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Index</h2></asp:Content>
如果要建無主版頁面面勾去select master page即可。
三、編輯Controller、View完成一個簡單的頁面傳值
我們將EiceController的Index改寫為
public class EiceController : Controller { public ActionResult Index(string id) { ViewData["chsword"] = id; return View(); } }
在View檔案即/Views/Eice/Index.aspx中改寫
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Index</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"><%=ViewData["chsword"] %></asp:Content>
下面我們來訪問/Eice/Index/HellowEice,可以看到:
這樣我們就將一個值從Url傳到Controller,又從Controller傳到View顯示出來。
由上面程式段可以看出Action的參數string id用於接收{Controller}/{Action}/{id}的ID部分
ViewData是一個頁面間的IDictionary用於Controller向View傳遞資料
這樣View與Controller就可以協作完成顯示頁面與邏輯處理的工作了
那除了ViewData之外我們還有什麼方法由Controller向View檔案傳值?我們除了能顯示aspx檔案外還能顯示其它的檔案嗎?
參考資料:pv版本Asp.net Mvc Framework 三 (Controller與View)