ASP.NET MVC 重點教程一周年版 第三回 Controller與View

來源:互聯網
上載者:User

這節我們讓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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.