發表文章

目前顯示的是 11月, 2020的文章

ASP.NET MVC第006天_ViewData,ViewBag,TempData用法與差異比較

圖片
在前幾篇有用到從Controller傳遞一些變數值給View的技巧 事實上在.net mvc中不只這一種方法 頁面間和Controller與View之間傳遞引數有幾種方式? Ans:共有4種ViewData,ViewBag,Session,TempData 基本上在ViewPage終究有明確定義如下幾種 能將資料Pass到View的屬性 ViewData Gets or sets a dictionary that contains data to pass between the controller and the view. public System . Web . Mvc . ViewDataDictionary ViewData { get ; set ; } 解釋: 自早期的asp.net MVC版本(1和2)就存在的一個ViewPage屬性, 屬於 Dictionary Object,衍生自 ViewDataDictionary ,能放入任何資料, 使用 Key / Value 的概念存取。 生命週期:僅存於當前的連線請求若發生網頁Redirect就會變Null。 (只有在從Controller到View中) 缺點: 1.值不能在多個請求中共享,不能跨Action傳遞資料,只能在一個Action有效。 (在重redirection後,ViewData中儲存的變數值將變為null。) 2.取出ViewData中的變數值後,必須進行合適的型別轉換(隱式或顯式)和null檢查。 3.沒有IntelliSense 用法: ViewData [ " KeyName " ] = XXX ViewBag Gets the view bag. public dynamic ViewBag { get ; } 解釋: 比較後期才添加的新屬性 跟ViewData有異曲同工之妙,屬於ViewData的封裝集合(把一堆ViewData打包裝放在一個包包)。 本質也是使用 Key / Value 存取,並能放入任何的資料, 而差異在於,它能產生「動態屬性」 (.net 4.0 dynamic) 。 也就是在runtime時候再判斷真正型別 (C# reflection) 生命週期:僅存於當前的連線請求若發生網頁Redirect就會變Nul