標籤:
一、使用Model
首先建立一個Model
public class HelloModel { private string _name;private string _text; public string Name { get { return _name; } set { _name = value; } } public string Text { get { return _text; } set { _text = value; } } } 然後建立強型別的View視圖,在View視圖中第一行寫@model Test.Models.HelloModel代表這個View使用的Model為“Test.Models.HelloModel”
在View中讀取Model中定義的資料,View中使用:@Html.Encode(Model.Name)
註:因為當字串中帶有空格或者<,這種可能引起瀏覽器曲解,就要加上Html.Encode進行Html編碼的轉換,以防出現一些不必要的錯誤。
二、使用ViewBag
ViewBag允許一個動態對象上定義任意屬性,並在視圖中訪問
Controller:
public ViewResult Index(){ViewBag.Message="Hello";ViewBag.Date=DateTime.Now;return View();} View中:
@{ViewBag.Title="Index";}<p>The message is:@ViewBag.Message</p><p>The day is:@ViewBag.Date.DayOfWeek</p>三、使用ViewData
Controller:
public ViewResult Index(){ViewData["Message"]="Hello";ViewData["Date"]=DateTime.Now;return View();} View中:
@{ViewBag.Title="Index";}<p>The message is:@ViewData["Message"]</p><p>The day is:@ViewData["Date"].DayOfWeek</p>
總結:
1. ViewData與TempData方式是弱類型的方式傳遞資料,而使用Model傳遞資料是強型別的方式。
2. ViewData與TempData是完全不同的資料類型,ViewData資料類型是ViewDataDictionary類的執行個體化對象,而TempData的資料類型是TempDataDictionary類的執行個體化對象。
TempData實際上儲存在Session中,控制器每次執行請求時都會從Session中擷取TempData資料並刪除該Session。TempData資料只能在控制器中傳遞一次,其中的每個元素也只能被訪問一次,訪問之後會被自動刪除。
ViewData只能在一個Action方法中進行設定,在相關的視圖頁面讀取,只對當前視圖有效。理論上,TempData應該可以在一個Action中設定,多個頁面讀取。但是,實際上TempData中的元素被訪問一次以後就會被刪除。
Asp.net MVC中Controller向View傳值