# [ASP.NET] ViewData、ViewBag、TempData 整理 ## 前言 對 ViewData、ViewBag、TempData 做簡單的整理,並且透過實作來熟悉。 ## 範例準備 建立範例用的 DataController和 Index、Read 的 Action,再建立對應的 View (Index.cshtml、Read.cshtml)。 * DataController.cs ```csharp= public class DataController : Controller { public ActionResult Index() { //範例學生資料 List<Student> data = new List<Student> { new Student { Id = 1, Name = "JJ" }, new Student { Id = 2, Name = "JJay" } }; return View(); } public ActionResult Read() { return View(); } } public class Student { public int Id { get; set; } public string Name { get; set; } } ``` 頁面說明: * Index Action 用來實作存放資料的邏輯。 * Read Action 及 Read.cshtml 用來實作資料的讀取。 ## ViewData 採用 key-value 的形式存放資料,型別為 ViewDataDictionary,本質上就是 Dictionary。 * 修改 Index Action,將 data 存放在 ViewData 中 ```csharp= public ActionResult Index() { List<Student> data = new List<Student> { new Student { Id = 1, Name = "JJ" }, new Student { Id = 2, Name = "JJay" } }; ViewData["Data"] = data; return View(); } ``` * 修改 Read.cshtml,利用 Razor 語法,在畫面端撰寫讀取邏輯 ```csharp= @{ List<Student> students = ViewData["Data"] as List<Student>; foreach (Student student in students) { <div>@student.Id--@student.Name</div> } /*輸出*/ //1--JJ //2--JJay } ``` <font color="red"> **注意:在讀取 ViewData 時,需要將資料進行轉型成強型別**</font> ## ViewBag 使用方式與 ViewData 相同,差別在於讀取時不需執行強型別的轉換。 * 修改 Action,根據 ViewData 的範例,改為以 ViewBag 存放 data 資料 ```csharp= public ActionResult Index() { List<Student> data = new List<Student> { new Student { Id = 1, Name = "JJ" }, new Student { Id = 2, Name = "JJay" } }; ViewBag["Data"] = data; return View(); } ``` * Read.cshtml ```csharp= @{ foreach (Student student in ViewBag["Data"]) { <div>@student.Id--@student.Name</div> } /*輸出*/ //1--JJ //2--JJay } ``` ## TempData TempData 的功能一樣是用來暫存資料,在使用時也需要轉型成強型別。 * Index Action 中的資料改以 TempData 存放 ```csharp= public ActionResult Index() { List<Student> data = new List<Student> { new Student { Id = 1, Name = "JJ" }, new Student { Id = 2, Name = "JJay" } }; TempData["Data"] = data; return View(); } ``` * Read.cshtml 讀取 ```csharp= @{ if(TempData("Data") != null) { foreach (Student student in TempData("Data")) { <div>@student.Id--@student.Name</div> } } /*輸出*/ //1--JJ //2--JJay } ``` * **TempData 使用上的重點紀錄** 1. 可跨請求來存取 TempData 的資料 2. 資料被讀取後就會被清空,所以讀取前要加上 Null 判斷 3. 若資料都沒有被讀取,則會保留到被讀取或 Session 過期為止 4. 若要在讀取後,仍保留資料,則需使用 Peek 或 Keep 方法 ### Peek 方法 Peek 可以用來讀取資料並且將其標示為保留,使用方法如下: ```csharp= var data = TempData.Peek("key"); /* * 參數:傳入資料的key * 回傳值:指定key存放的資料 * */ ``` ### Keep 方法 Keep 可以在讀取資料過後,標視為保留,使用方法如下 ```csharp= var data = TempData["key"]; TempData.Keep("key"); ``` ###### tags: `ASP.NET` `MVC`
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.