ViewData、ViewBag、TempData 三者的應用:
- ViewData 該頁面傳遞參數。
- ViewBag 可以動態產生 動態屬性 (dynamic型別)傳遞參數。
- TempData 可跨Action傳遞參數。
展示三種範例:
- 一般傳遞參數
- Object傳遞參數
- 跨Action傳遞參數
ViewData、ViewBag、TempData 一般傳遞參數
Controller
public ActionResult Index() { ViewData["message"] = "訊息"; ViewBag.message = "訊息"; TempData["message"] = "訊息"; return View(); }
View
<h2>Index</h2> ViewData = @ViewData["message"] <br /> ViewBag = @ViewBag.message <br /> TempData = @TempData["message"]
執行結果
ViewData、ViewBag、TempData Object傳遞參數
Model
新增一個 Product.cs
public class Product { public int Id { get; set; } public string Name { get; set; } public string Type { get; set; } }
Controller
public ActionResult Index() { Product product = new Product(); product.Id = 2; product.Name = "草莓大福"; product.Type = "K001"; ViewBag.Product = product; ViewData["product"] = product; TempData["product"] = product; return View(); }
View
@using Models; @{ //ViewBag Product ViewBagProduct = ViewBag.Product; //ViewData Product ViewDataProduct = (Product)ViewData["product"]; //TempData Product TempDataProduct = (Product)TempData["product"]; } <h2>Index</h2> ViewBag:@ViewBagProduct.Name <br /> ViewData:@ViewDataProduct.Name <br /> TempData = @TempDataProduct.Name
執行結果
ViewData、ViewBag、TempData 跨Action傳遞參數
Controller
public ActionResult Index() { ViewData["Index"] = "ViewData IndexPage"; ViewBag.Index = "ViewBag IndexPage"; TempData["Index"] = "TempData IndexPage"; return RedirectToAction("TempDataPage"); }
View
新增TempDataPage.cshtml
<h2>TempDataPage</h2> ViewData = @ViewData["Index"] <br /> ViewBag = @ViewBag.Index <br /> TempData = @TempData["Index"]
執行結果
沒有留言:
張貼留言