Controller向View傳遞資料

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   ar   strong   資料   

1.       使用ViewData傳遞資料

我們在Controller中定義如下:

ViewData[“Message”] = “Hello word!”;

然後在View中讀取Controller中定義的ViewData資料,代碼如下:

<% = Html.Encode(ViewData[“Message”]) %>

2.       使用TempData傳遞資料

我們在Controller中定義如下:

TempData[“Message”] = “Hello word!”;

然後在View中讀取Controller中定義的TempData資料,代碼如下:

<% = Html.Encode(TempData [“Message”]) %>

3.       使用Model傳遞資料

使用Model傳遞資料的時候,通常在建立View的時候我們會選擇建立強型別View如所示:

建立強型別的View以後,View的第一行代碼如下所示:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcInduction.Models.People>" %>

<MvcInduction.Models.People>就代表了這個View使用的Model為“MvcInduction.Models.People”

 

總結:

1.         ViewData與TempData方式是弱類型的方式傳遞資料,而使用Model傳遞資料是強型別的方式。

2.         ViewData與TempData是完全不同的資料類型,ViewData資料類型是ViewDataDictionary類的執行個體化對象,而TempData的資料類型是TempDataDictionary類的執行個體化對象。

3.         TempData實際上儲存在Session中,控制器每次執行請求時都會從Session中擷取TempData資料並刪除該Session。TempData資料只能在控制器中傳遞一次,其中的每個元素也只能被訪問一次,訪問之後會被自動刪除。

4.         ViewData只能在一個Action方法中進行設定,在相關的視圖頁面讀取,只對當前視圖有效。理論上,TempData應該可以在一個Action中設定,多個頁面讀取。但是,實際上TempData中的元素被訪問一次以後就會被刪除。

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.