爲尊重原創精神,本文內容所有轉自「光頭毅」博客(連接地址-->Url)。html
在MVC中,Controller與View之間的傳值有如下幾種方式:瀏覽器
ViewDatamvc
ViewBagapp
TempDataide
Sessionspa
ViewData和ViewBag實際上是一回事,ViewBag實際上是對ViewData的封裝,其內部其實使用的是ViewData實現數據存儲的。惟一不一樣的是,ViewBag能夠存儲動態類型(dynamic),而ViewData只能存儲string(Key)/Object(value)字典集合。3d
1 ViewData["Message"]="Hello Word!"; 2 3 //Or 4 5 ViewBag.Message="Hello Word!";
TempData也是一個string(Key)/object(value)的字典集合,可是和ViewData、ViewBag不一樣的是其存儲的數據對象的生命週期。若是發生了頁面跳轉(Redirection),ViewData和ViewBag中的值將不復存在,可是TempData的值依然還存在。換句話講,ViewBag和ViewData的生命週期只有在從Controller到View中,而TempData的數據不只在Controller到View中有效,在不一樣Action或者從一個頁面跳轉到另外一個頁面(Controller to Controller)後依然有效。code
1 TempData["Message"]="Hello World!";
Session其實和ViewData類型,也是一個string(Key)/object(value)的字典集合,可是Session只存儲在客戶端的Cookies中,因此它的生命週期是最長的,可是也正是由於其存儲在客戶端,全部一些敏感的機密信息是不能存儲在裏面的。htm
特色:對象
1.ViewData是一個繼承於ViewDataDictionary類的Dictionary對象。
2.ViewData用來從Controller向對應的View傳值。
3.ViewData只有在當前請求中有效,生命週期與View相同,其值不能在多個請求中共享。
4.在重定向後(Redirection),ViewData存儲的值變爲null
5.在取出ViewData的變量值,必須進行合適的類型轉換和空值檢查
例子:
<html> <head> <meta name="view-port" content="width=device-wodth"/> <title>Index</Index> </head> <body> <div> @ViewData["Message"].ToString() </div> </body> </html>
Controller Code:
1 public ActionResult Index() 2 { 3 ViewData["Message"]="Hello World!"; 4 return View(); 5 }
效果:
注意:在從ViewData中取出變量Message時沒有對其中進行類型轉換,由於咱們存儲的是簡單類型,若是是負責類型,必須進行類型轉換。
特色:
1.ViewBag是一個動態類型變量(dynamic),變量類型在運行時會進行解析。
2.ViewBag其餘跟ViewData差很少。
3.ViewBag是動態類型,因此在取值時,不須要進行類型轉換。
例子:
1 public ActionResult Index() 2 { 3 ViewBag.Message = "This is a message from ViewBag"; 4 5 return View(); 6 }
在瀏覽器中瀏覽時,以下圖:
特色:
1.TempData是一個繼承TempDataDictionary的字典集合對象,它默認狀況是基於Session存儲機制之上(備註:你也可讓你的TempData基於其餘存儲機制之上,咱們能夠提供自定義的ITempDataProvider來完成)
2.TempData用來多個Action 或 從當前請求指向子請求,或者 頁面發生了重定向(Redirection)時傳遞共享數據。
3.只有在目標視圖(View)加載完畢後,纔能有效。
4.在取出TempData的變量時,須要進行合適的類型轉換。
例子:
1 public class Customer 2 { 3 public int ID { get; set; } 4 public string Name { get; set; } 5 }
1 public ActionResult DisplayCustomer1() 2 { 3 Customer customer = new Customer 4 { 5 Id = 1001, 6 Code = "100101", 7 Amount = 100 8 }; 9 10 TempData["OneCustomer"] = customer; 11 12 return RedirectToAction("DisplayCustomer2"); 13 } 14 15 public ActionResult DisplayCustomer2() 16 { 17 Customer customer = TempData["OneCustomer"] as Customer; 18 19 return View(customer); 20 }
html:
結果:
特色:
1.Session也是MVC中用來傳值的一種方式,但與TempData不一樣的是,用戶的整個會話過程當中,Session都不會過時。
2.Session在同一用戶會話過程當中的全部請求中有效,好比:刷新頁面
3.Sessiion的值也須要進行類型轉換和檢查。
例子:
1 public ActionResult DisplayCustomer1() 2 { 3 Customer customer = new Customer 4 { 5 Id = 1001, 6 Code = "100101", 7 Amount = 100 8 }; 9 10 Session["OneCustomer"] = customer; 11 12 return RedirectToAction("DisplayCustomer2"); 13 } 14 15 public ActionResult DisplayCustomer2() 16 { 17 Customer customer = Session["OneCustomer"] as Customer; 18 19 return View(customer); 20 }