21 April 2015

ASP.NET MVC : ViewData VS ViewBag Vs TempData

   สวัสดีครับ บทความนี้ผมจะมาเขียนเกี่ยวกับการใช้ ViewData, ViewBag และ TempData ทั้งการใช้งานและข้อแตกต่างแบบคร่าวๆ
   ViewData ใช้สำหรับส่งข้อมูลจาก Controller ไปยัง View ค่าที่เก็บใน ViewData จะหายไปเมื่อมีการ Redirect ไปยัง Action อื่นๆ
Controller
public ActionResult Index()
{
ViewData["MyDateTime"] = DateTime.Now;
return View();
}
view raw gistfile1.cs hosted with ❤ by GitHub
View
<div>
<label>ViewData </label>@ViewData["MyDateTime"]
</div>
view raw gistfile1.html hosted with ❤ by GitHub
   ViewBag ใช้สำหรับส่งข้อมูลจาก Controller ไปยัง View เช่นเดียวกับ ViewData แต่จะสามารถใช้ได้กับ .Net Framework 4.0 ขึ้นไปและยังเป็น Dynamic property ของ ControllerBase class
Controller
public ActionResult Index()
{
ViewBag.MyDateTime = DateTime.Now;
return View();
}
view raw gistfile1.cs hosted with ❤ by GitHub
View
<div>
<label>ViewBag </label>@ViewBag.MyDateTime
</div>
view raw gistfile1.html hosted with ❤ by GitHub
   TempData มีความแตกต่างจาก ViewData และ ViewBag สามารถส่งข้อมูลจาก Controller ไปยัง View และยังสามารถส่งข้อมูลจาก Action ไปยัง Action ได้ด้วย แต่ว่า TempData จะมีช่วงเวลาการเก็บข้อมูลที่สั้นมาก
Controller
public ActionResult Index()
{
TempData["MyDateTime"] = DateTime.Now;
return View();
}
view raw gistfile1.cs hosted with ❤ by GitHub
View
<div>
<label>TempData </label>@TempData["MyDateTime"]
</div>
view raw gistfile1.html hosted with ❤ by GitHub
Pass data from action to action.
public ActionResult Index()
{
TempData["MyDateTime"] = DateTime.Now;
return RedirectToAction("Index2");
}
public ActionResult Index2()
{
DateTime myDateTime = Convert.ToDateTime(TempData["MyDateTime"]);
return View();
}
view raw gistfile1.cs hosted with ❤ by GitHub
Ref. - http://www.c-sharpcorner.com/Blogs/12427/viewdata-vs-viewbag-vs-tempdata-in-mvc.aspx
Ref. - http://www.dotnet-tricks.com/Tutorial/mvc/9KHW190712-ViewData-vs-ViewBag-vs-TempData-vs-Session.html
Ref. - http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-2cplusViewBagplusandplusTem