ASP.NET MVC第006天_ViewData,ViewBag,TempData用法與差異比較
在前幾篇有用到從Controller傳遞一些變數值給View的技巧
事實上在.net mvc中不只這一種方法
頁面間和Controller與View之間傳遞引數有幾種方式?
Ans:共有4種ViewData,ViewBag,Session,TempData
基本上在ViewPage終究有明確定義如下幾種
能將資料Pass到View的屬性
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
Gets the view bag.
public dynamic ViewBag { get; }
解釋:
比較後期才添加的新屬性
跟ViewData有異曲同工之妙,屬於ViewData的封裝集合(把一堆ViewData打包裝放在一個包包)。
本質也是使用 Key / Value 存取,並能放入任何的資料,
而差異在於,它能產生「動態屬性」(.net 4.0 dynamic)。
也就是在runtime時候再判斷真正型別 (C# reflection)
生命週期:僅存於當前的連線請求若發生網頁Redirect就會變Null。
(只有在從Controller到View中)
缺點:
1.值不能在多個請求中共享,不能跨Action傳遞資料,只能在一個Action有效。
(在重redirection後,ViewData中儲存的變數值將變為null。)
2.動態的屬性沒有IntelliSense ,需額外先強制轉型才有。
用法:
ViewBag.KeyName = XXX
提醒:
1.ViewBag 和 ViewData 的Key是共用的。
所以若使用 ViewData["Country"] = "Japan" 而後面又寫 ViewBag.Country= "Korea" ,
則最後使用到 key 值為 Country的資料就會變成 Korea。
2.要注意 key 值是唯一的不能重複,如果重複使用就會被覆蓋掉。
3.Key值不區分大小寫(例如: Address 會等同於 address)
程式碼的案例
HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MyEmptyMVC1.Controllers
- {
- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- #region 用ViewData來Pass值
- ViewData["DatetimeNow"] = DateTime.Now;
- ViewData["Address"] = "臺北市信義區市府路1號";
- ViewData["Years"] = 28;
- ViewData["Percent"] = 0.85;
- ViewData["UnitPrice"] = 80;
- ViewData["CountOfOneWeek"] = 5;
- List<string> lsFruit = new List<string>();
- lsFruit.Add("Orange");
- lsFruit.Add("Banana");
- lsFruit.Add("Peach");
- ViewData["FruitList"] = lsFruit;
- DataTable dt = new DataTable();
- dt.Columns.Add("Name");
- dt.Columns.Add("Title");
- dt.Columns.Add("Years");
- DataRow row1 = dt.NewRow();
- row1["Name"] = "Amy";
- row1["Title"] = "會計";
- row1["Years"] = 5;
- dt.Rows.Add(row1);
- DataRow row2 = dt.NewRow();
- row2["Name"] = "Jack";
- row2["Title"] = "工程師";
- row2["Years"] = 8;
- dt.Rows.Add(row2);
- ViewData["EmployeeInfo"] = dt;
- #endregion
- #region 用ViewBag來Pass值
- ViewBag.NowDate = DateTime.Now.Date;
- ViewBag.address = "台北市萬華";
- ViewBag.Num = 7;
- ViewBag.PI = 3.1415;
- List<string> lsWeek = new List<string>();
- lsWeek.Add("Monday");
- lsWeek.Add("Tuesday");
- lsWeek.Add("Wednesday");
- lsWeek.Add("Thursday");
- lsWeek.Add("Friday");
- lsWeek.Add("Saturday");
- lsWeek.Add("Sunday");
- ViewBag.WeekDay = lsWeek;
- DataTable dtScore = new DataTable();
- dtScore.Columns.Add("Name");
- dtScore.Columns.Add("Grade");
- dtScore.Columns.Add("Score");
- DataRow dr1 = dtScore.NewRow();
- dr1["Name"] = "Tom";
- dr1["Grade"] = "一年級";
- dr1["Score"] = 82;
- dtScore.Rows.Add(dr1);
- DataRow dr2 = dtScore.NewRow();
- dr2["Name"] = "Jason";
- dr2["Grade"] = "一年級";
- dr2["Score"] = 89;
- dtScore.Rows.Add(dr2);
- DataRow dr3 = dtScore.NewRow();
- dr3["Name"] = "Mike";
- dr3["Grade"] = "二年級";
- dr3["Score"] = 93;
- dtScore.Rows.Add(dr3);
- DataRow dr4 = dtScore.NewRow();
- dr4["Name"] = "Jason";
- dr4["Grade"] = "二年級";
- dr4["Score"] = 98;
- dtScore.Rows.Add(dr4);
- ViewBag.ScoreTable = dtScore;
- #endregion
- return View();
- }
- }
- }
Index.cshtml
- @{
- Layout = null;
- }
- @using System.Data; @*for DataTable,DataRow,DataSet用*@
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <div>
- 用ViewData來Pass值<br />
- 現在時間:@ViewData["DatetimeNow"]<br />
- 住址:@ViewData["Address"]<br />
- 年齡:@ViewData["Years"]<br />
- 百分比:@ViewData["Percent"]<br />
- 一週上班午餐餐費(週一至周五)_不會印出計算結果: @ViewData["UnitPrice"] * @ViewData["CountOfOneWeek"] <br />
- @*Razor中直接返回運算結果要用@(....) 包覆,ViewData記得做Cast轉型*@
- 一週上班午餐餐費(週一至周五)_會印出計算結果: @( (int)@ViewData["UnitPrice"] * (int)@ViewData["CountOfOneWeek"] ) <br />
- 水果清單:<br />
- <ul>
- @foreach (string item in (List<string>)ViewData["FruitList"])
- {
- <li>@item</li>
- }
- </ul>
- <table>
- <tr>
- <th>職員姓名</th>
- <th>職稱</th>
- <th>年資</th>
- </tr>
- @*在一開始記得引入@using System.Data;*@
- @foreach (DataRow item in (ViewData["EmployeeInfo"] as DataTable).Rows)
- {
- <tr>
- <td>@item["Name"]</td>
- <td>@item["Title"]</td>
- <td>@item["Years"]</td>
- </tr>
- }
- </table>
- 用ViewBag來Pass值<br />
- 今天日期:@ViewBag.NowDate<br />
- 住址(用小寫):@ViewBag.address<br />
- 住址(用大寫第一個開頭)_觀察Key大小寫有無差別:@ViewData["Address"]<br />
- 住址(用大寫第一個開頭)_觀察ViewBag跟ViewData是否Key共用:@ViewBag.Address<br />
- 一週有 @ViewBag.Num 天 <br />
- 圓周率:@ViewBag.PI <br />
- <ol>
- @foreach (string item in (List<string>)ViewBag.WeekDay)
- {
- <li>@item</li>
- }
- </ol>
- <h3>學生成績清單</h3>
- <dl>
- @foreach(DataRow item in ((DataTable)ViewBag.ScoreTable).Rows)
- {
- <dt>@item["Grade"] </dt>
- <dd>@item["Name"]</dd>
- <dd>@item["Score"]</dd>
- }
- </dl>
- </div>
- </body>
- </html>
運行結果
會發現第17行Address
ViewData["Address"] = "臺北市信義區市府路1號";
已經被第51行的用小寫開頭的ViewBag給覆蓋掉了
ViewBag.address = "台北市萬華";
驗證了
1.ViewBag 和 ViewData 的Key是共用的。
3.Key值不區分大小寫(例如: Address 會等同於 address)
此外印出一週餐費的View中調用的寫法
Razor中直接返回運算結果要用@(....) 包覆,ViewData記得做Cast轉型。
Gets the temporary data to pass to the view.
TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
public System.Web.Mvc.TempDataDictionary TempData { get; }
TempData也是 Dictionary 類別, 衍生自 TempDataDictionary 纇, 要注意字典資料轉型跟Null問題。
有別於ViewData與ViewBag,差異點在於所儲存的資料物件的生命週期。
如果頁面發生了跳轉(Redirection),ViewBag和ViewData中的值將不復存在,
但是TempData中的值依然還在。
當你希望僅在一個HTTP 請求和下一個 HTTP 請求之間保留資料時,可以使用 TempData 。
換言之, ViewBag和ViewData儲存的值的生命週期只有在從Controller到View中,
而TempData中的資料不僅在從Controller到View中有效,
在不同的Action之間或者從一個頁面跳轉到另一頁面(Controller to Controller)後依然有效。
生命週期:除了當下請求, 導頁後仍可續存 (如action to action, controller to action),但如果在View中一被讀取(或顯示出來)就會被刪除。
(TempData中資料只要一被讀取過就會被標記為已用過要被刪除。)
優點:
可跨controller,跨action,不僅僅只是單向的從Controller到View。
缺點:
1.取出TempData中的變數值後,必須進行合適的型別轉換(隱式或顯式)和null檢查。
2.沒有IntelliSense
程式碼的案例
在HomeController新增兩動作(Page1, Page2)和相應的View
下中斷點執行測試
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MyEmptyMVC1.Controllers
- {
- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult Page1()
- {
- TempData["datetime"] = DateTime.Now;
- TempData["TmpData"] = "Tmp Data A";
- ViewData["vd_data"] = "test viewdata A";
- ViewBag.vb_data = "test viewbagdata A";
- return RedirectToAction("Page2");
- }
- public ActionResult Page2()
- {
- string str = TempData["datetime"].ToString();
- string str1 = TempData["TmpData"].ToString();
- string str_view_data = ViewData["vd_data"]?.ToString();
- string str_view_bag = ViewBag.vb_data?.ToString();
- return View("Page1");
- }
- }
- }
運行結果測試
一開始進到Page1 的Action
隨後又Redirect到另一Action時候,就會發現只剩下TempData仍保存上一次Request的值。
TempData還有一個重點就在於之所以被稱作為TempData的原因在於
被寫入的資料在第一次讀取的時候就會被刪除了。
(儲存到 TempData 的資料會存放在Session中,並將在訪問資料的第一個請求結束時自動刪除。
如果從未讀過,它將一直保留到最後一次讀取或session timeout。)
在這幾篇都有被特別提到
ASP.NET MVC 系列4 - ViewData與TempData
這次針對TempData修改一下例子觀察
若是於Page1, Page2都直接讀取TempData會有捨麼情況
測試Page1 -> Page2的導向過程中TempData的生命週期
Page1.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page1</title>
- </head>
- <body>
- <div>
- <h1>Page1</h1>
- Now Time:@TempData["datetime"]
- <br />
- TmpData:@TempData["TmpData"]
- <br />
- @Html.ActionLink("連結到Page2","Page2","Home")
- </div>
- </body>
- </html>
Page2.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page2</title>
- </head>
- <body>
- <div>
- <h1>Page2</h1>
- Now Time:@TempData["datetime"]
- <br />
- TmpData:@TempData["TmpData"]
- </div>
- </body>
- </html>
HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MyEmptyMVC1.Controllers
- {
- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- #region 用ViewData來Pass值
- ViewData["DatetimeNow"] = DateTime.Now;
- ViewData["Address"] = "臺北市信義區市府路1號";
- ViewData["Years"] = 28;
- ViewData["Percent"] = 0.85;
- ViewData["UnitPrice"] = 80;
- ViewData["CountOfOneWeek"] = 5;
- List<string> lsFruit = new List<string>();
- lsFruit.Add("Orange");
- lsFruit.Add("Banana");
- lsFruit.Add("Peach");
- ViewData["FruitList"] = lsFruit;
- DataTable dt = new DataTable();
- dt.Columns.Add("Name");
- dt.Columns.Add("Title");
- dt.Columns.Add("Years");
- DataRow row1 = dt.NewRow();
- row1["Name"] = "Amy";
- row1["Title"] = "會計";
- row1["Years"] = 5;
- dt.Rows.Add(row1);
- DataRow row2 = dt.NewRow();
- row2["Name"] = "Jack";
- row2["Title"] = "工程師";
- row2["Years"] = 8;
- dt.Rows.Add(row2);
- ViewData["EmployeeInfo"] = dt;
- #endregion
- #region 用ViewBag來Pass值
- ViewBag.NowDate = DateTime.Now.Date;
- ViewBag.address = "台北市萬華";
- ViewBag.Num = 7;
- ViewBag.PI = 3.1415;
- List<string> lsWeek = new List<string>();
- lsWeek.Add("Monday");
- lsWeek.Add("Tuesday");
- lsWeek.Add("Wednesday");
- lsWeek.Add("Thursday");
- lsWeek.Add("Friday");
- lsWeek.Add("Saturday");
- lsWeek.Add("Sunday");
- ViewBag.WeekDay = lsWeek;
- DataTable dtScore = new DataTable();
- dtScore.Columns.Add("Name");
- dtScore.Columns.Add("Grade");
- dtScore.Columns.Add("Score");
- DataRow dr1 = dtScore.NewRow();
- dr1["Name"] = "Tom";
- dr1["Grade"] = "一年級";
- dr1["Score"] = 82;
- dtScore.Rows.Add(dr1);
- DataRow dr2 = dtScore.NewRow();
- dr2["Name"] = "Jason";
- dr2["Grade"] = "一年級";
- dr2["Score"] = 89;
- dtScore.Rows.Add(dr2);
- DataRow dr3 = dtScore.NewRow();
- dr3["Name"] = "Mike";
- dr3["Grade"] = "二年級";
- dr3["Score"] = 93;
- dtScore.Rows.Add(dr3);
- DataRow dr4 = dtScore.NewRow();
- dr4["Name"] = "Jason";
- dr4["Grade"] = "二年級";
- dr4["Score"] = 98;
- dtScore.Rows.Add(dr4);
- ViewBag.ScoreTable = dtScore;
- #endregion
- return View();
- }
- public ActionResult Page1()
- {
- TempData["datetime"] = DateTime.Now;
- TempData["TmpData"] = "Tmp Data A";
- return View();
- }
- public ActionResult Page2()
- {
- return View();
- }
- }
- }
就會發現第一次導向Page1時候
原存於TempData的值
再點導向Page2的link後就不見了
View讀取一次對應的TempData後即從TempData集合中刪除,
不過如果TempData未被View讀取之前,其值可在Controller之間傳遞直到session timeout。
下圖為TempData 完整生命週期示意圖
摘自:
若不想TempData被View讀取使用後就被刪除,可透過如下兩種保存機制
1.使用TempData.Peek來長期儲存。
2.若是只想再儲存一次,之後被View再次讀取後就刪除則要使用TempData.Keep。
四種情境的說明
1. Not Read in First Request :
If we do not read “TempData” in the current request then “TempData” value will be persisted for the next request.
2.Read In First Request :
If we read “TempData” in the current request then “TempData” value will be not persist for the next request.
3.Read & Persist using Keep :
If we read “TempData” in the current request and we can keep method to persist TempData for the next request. In MVC, we are having void keep() and void keep(string key) methods to persist the data.
4.Peek and Read:
If you set a TempData in your action method and if you read it in your view by calling "Peek" method then TempData will be persisted and will be available in next request.
TempData.Keep使用方式
Keep() method marks the specified key in the dictionary for retention
主要功能是將被標註狀態為要刪除的資料恢復成不被刪除狀態
有分
保留特定Key的
public void Keep(string key);
跟全部保留的
public void Keep();
來測試Page1 -> Page2 -> Page3的導向過程中TempData使用Keep的生命週期
Page1.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page1</title>
- </head>
- <body>
- <div>
- <h1>Page1</h1>
- Now Time:@TempData["datetime"]
- <br />
- TmpData:@TempData["TmpData"]
- <br />
- @Html.ActionLink("連結到Page2","Page2","Home")
- </div>
- </body>
- </html>
Page2.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page2</title>
- </head>
- <body>
- <div>
- <h1>Page2</h1>
- Now Time:@TempData["datetime"]
- <br />
- TmpData:@TempData["TmpData"]
- <br />
- @Html.ActionLink("連結到Page3", "Page3", "Home")
- </div>
- </body>
- </html>
Page3.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page3</title>
- </head>
- <body>
- <div>
- <h1>Page3</h1>
- Now Time:@TempData["datetime"]
- <br />
- TmpData:@TempData["TmpData"]
- </div>
- </body>
- </html>
HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MyEmptyMVC1.Controllers
- {
- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- #region 用ViewData來Pass值
- ViewData["DatetimeNow"] = DateTime.Now;
- ViewData["Address"] = "臺北市信義區市府路1號";
- ViewData["Years"] = 28;
- ViewData["Percent"] = 0.85;
- ViewData["UnitPrice"] = 80;
- ViewData["CountOfOneWeek"] = 5;
- List<string> lsFruit = new List<string>();
- lsFruit.Add("Orange");
- lsFruit.Add("Banana");
- lsFruit.Add("Peach");
- ViewData["FruitList"] = lsFruit;
- DataTable dt = new DataTable();
- dt.Columns.Add("Name");
- dt.Columns.Add("Title");
- dt.Columns.Add("Years");
- DataRow row1 = dt.NewRow();
- row1["Name"] = "Amy";
- row1["Title"] = "會計";
- row1["Years"] = 5;
- dt.Rows.Add(row1);
- DataRow row2 = dt.NewRow();
- row2["Name"] = "Jack";
- row2["Title"] = "工程師";
- row2["Years"] = 8;
- dt.Rows.Add(row2);
- ViewData["EmployeeInfo"] = dt;
- #endregion
- #region 用ViewBag來Pass值
- ViewBag.NowDate = DateTime.Now.Date;
- ViewBag.address = "台北市萬華";
- ViewBag.Num = 7;
- ViewBag.PI = 3.1415;
- List<string> lsWeek = new List<string>();
- lsWeek.Add("Monday");
- lsWeek.Add("Tuesday");
- lsWeek.Add("Wednesday");
- lsWeek.Add("Thursday");
- lsWeek.Add("Friday");
- lsWeek.Add("Saturday");
- lsWeek.Add("Sunday");
- ViewBag.WeekDay = lsWeek;
- DataTable dtScore = new DataTable();
- dtScore.Columns.Add("Name");
- dtScore.Columns.Add("Grade");
- dtScore.Columns.Add("Score");
- DataRow dr1 = dtScore.NewRow();
- dr1["Name"] = "Tom";
- dr1["Grade"] = "一年級";
- dr1["Score"] = 82;
- dtScore.Rows.Add(dr1);
- DataRow dr2 = dtScore.NewRow();
- dr2["Name"] = "Jason";
- dr2["Grade"] = "一年級";
- dr2["Score"] = 89;
- dtScore.Rows.Add(dr2);
- DataRow dr3 = dtScore.NewRow();
- dr3["Name"] = "Mike";
- dr3["Grade"] = "二年級";
- dr3["Score"] = 93;
- dtScore.Rows.Add(dr3);
- DataRow dr4 = dtScore.NewRow();
- dr4["Name"] = "Jason";
- dr4["Grade"] = "二年級";
- dr4["Score"] = 98;
- dtScore.Rows.Add(dr4);
- ViewBag.ScoreTable = dtScore;
- #endregion
- return View();
- }
- public ActionResult Page1()
- {
- TempData["datetime"] = DateTime.Now;
- TempData["TmpData"] = "Tmp Data A";
- TempData.Keep("datetime");//將字典中指定的索引鍵標記為保留。
- //TempData.Keep();//將字典中的所有索引鍵都標記為保留。
- return View();
- }
- public ActionResult Page2()
- {
- return View();
- }
- public ActionResult Page3()
- {
- return View();
- }
- }
- }
我們可以拿一個資料做TempData Keep的測試
會觀察到Now Time的值在導向到Page2後仍存在
Page1 -> Page2 -> Page3的導向過程
但在從Page2導向到Page3就消失了
Page1 -> Page2 -> Page3的導向過程
在被View讀取後,Keep只會被保留一次,然後就刪除了。
TempData.Peek使用方式
Peek() method returns an object that contains the element that is associated with the specified key, without marking the key for deletion
主要功能是用不標註狀態要刪除的方式取值
這裡改用Peek來測試效果
Page1.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page1</title>
- </head>
- <body>
- <div>
- <h1>Page1</h1>
- Now Time:@TempData.Peek("datetime").ToString()
- <br />
- TmpData:@TempData["TmpData"]
- <br />
- @Html.ActionLink("連結到Page2","Page2","Home")
- </div>
- </body>
- </html>
Page2.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page2</title>
- </head>
- <body>
- <div>
- <h1>Page2</h1>
- Now Time:@TempData.Peek("datetime").ToString()
- <br />
- TmpData:@TempData["TmpData"]
- <br />
- @Html.ActionLink("連結到Page3", "Page3", "Home")
- </div>
- </body>
- </html>
Page3.cshtml
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Page3</title>
- </head>
- <body>
- <div>
- <h1>Page3</h1>
- Now Time:@TempData.Peek("datetime").ToString()
- <br />
- TmpData:@TempData["TmpData"]
- </div>
- </body>
- </html>
HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MyEmptyMVC1.Controllers
- {
- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- #region 用ViewData來Pass值
- ViewData["DatetimeNow"] = DateTime.Now;
- ViewData["Address"] = "臺北市信義區市府路1號";
- ViewData["Years"] = 28;
- ViewData["Percent"] = 0.85;
- ViewData["UnitPrice"] = 80;
- ViewData["CountOfOneWeek"] = 5;
- List<string> lsFruit = new List<string>();
- lsFruit.Add("Orange");
- lsFruit.Add("Banana");
- lsFruit.Add("Peach");
- ViewData["FruitList"] = lsFruit;
- DataTable dt = new DataTable();
- dt.Columns.Add("Name");
- dt.Columns.Add("Title");
- dt.Columns.Add("Years");
- DataRow row1 = dt.NewRow();
- row1["Name"] = "Amy";
- row1["Title"] = "會計";
- row1["Years"] = 5;
- dt.Rows.Add(row1);
- DataRow row2 = dt.NewRow();
- row2["Name"] = "Jack";
- row2["Title"] = "工程師";
- row2["Years"] = 8;
- dt.Rows.Add(row2);
- ViewData["EmployeeInfo"] = dt;
- #endregion
- #region 用ViewBag來Pass值
- ViewBag.NowDate = DateTime.Now.Date;
- ViewBag.address = "台北市萬華";
- ViewBag.Num = 7;
- ViewBag.PI = 3.1415;
- List<string> lsWeek = new List<string>();
- lsWeek.Add("Monday");
- lsWeek.Add("Tuesday");
- lsWeek.Add("Wednesday");
- lsWeek.Add("Thursday");
- lsWeek.Add("Friday");
- lsWeek.Add("Saturday");
- lsWeek.Add("Sunday");
- ViewBag.WeekDay = lsWeek;
- DataTable dtScore = new DataTable();
- dtScore.Columns.Add("Name");
- dtScore.Columns.Add("Grade");
- dtScore.Columns.Add("Score");
- DataRow dr1 = dtScore.NewRow();
- dr1["Name"] = "Tom";
- dr1["Grade"] = "一年級";
- dr1["Score"] = 82;
- dtScore.Rows.Add(dr1);
- DataRow dr2 = dtScore.NewRow();
- dr2["Name"] = "Jason";
- dr2["Grade"] = "一年級";
- dr2["Score"] = 89;
- dtScore.Rows.Add(dr2);
- DataRow dr3 = dtScore.NewRow();
- dr3["Name"] = "Mike";
- dr3["Grade"] = "二年級";
- dr3["Score"] = 93;
- dtScore.Rows.Add(dr3);
- DataRow dr4 = dtScore.NewRow();
- dr4["Name"] = "Jason";
- dr4["Grade"] = "二年級";
- dr4["Score"] = 98;
- dtScore.Rows.Add(dr4);
- ViewBag.ScoreTable = dtScore;
- #endregion
- return View();
- }
- public ActionResult Page1()
- {
- TempData["datetime"] = DateTime.Now;
- TempData["TmpData"] = "Tmp Data A";
- //TempData.Keep("datetime");//將字典中指定的索引鍵標記為保留。
- //TempData.Keep();//將字典中的所有索引鍵都標記為保留。
- return View();
- }
- public ActionResult Page2()
- {
- return View();
- }
- public ActionResult Page3()
- {
- return View();
- }
- }
- }
就可以持續保留
上述這幾項都是適用在資料傳輸量不會太多的情況
若要傳輸較大量資料建議用ViewModel
參考此篇的建議
Ref:
How to Persist Data with TempData using Peek and Keep in MVC
MVC: WHEN TO USE KEEP() VS PEEK() WITH TEMPDATA IN ASP.NET MVC
MVC TempData – Peek vs Keep
Difference between TempData keep() And Peek() in Asp.Net MVC
ASP.NET MVC ViewData 與 TempData 的差別
Tempdata keep与peek
[創意料理] 再深入一點點對 ViewBag、ViewData、Model 的了解
[ASP.NET MVC] ASP.NET MVC 傳遞資料容器(一) - ViewData vs ViewBag
[探索 10 分鐘] 寫點有關 ASP.NET MVC ViewModel, ViewData, ViewBag, TempData 的代碼
asp.net mvc. Passing a list via viewData
What is the right time for ViewData, ViewBag, Session, TempData
When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications
Difference Between ViewData, ViewBag, TemData and Session in MVC
MVC传值方式及优缺点
TempData 生命週期
認識Controller - 傳資料給View
ASP.NET MVC中controller和view相互傳值的方式
從零開始的MVC開發-Controller對View的喊話
留言
張貼留言