1.ViewData
1.1 ViewData繼承了IDictionary<string, object>,因此在設置ViewData屬性時,傳入key必須要字符串型別,value可以是任意類型。
1.2 ViewData它只會存在這次的HTTP要求而已,而不像Session可以將數據帶到下HTTP要求。
public class TestController : Controller{public ActionResult Index(){ViewData["msg"] = "123123";return View();}}
@{ViewBag.Title = "Index"; }<h2>頁面</h2> <h2>@ViewData["msg"]</h2>
?
2.ViewData的擴張屬性ViewData.Model
public class TestController : Controller{public ActionResult Index(){User aa = new User() { Age = 1, Name = "linq" };//ViewData.Model = aa;return View(aa);}}
@{ViewBag.Title = "Index"; } @model MvcApplication1.Models.User <h2>頁面</h2> <h2>@Model.Age</h2> <h2>@Model.Name</h2>
3.ViewBag
3.1 嚴格來說ViewBag和ViewData的區別就是ViewBag是dynamic動態型別
public class TestController : Controller{public ActionResult Index(){User aa = new User() { Age = 1, Name = "linq" };ViewBag.User = aa;return View();}}
@{ViewBag.Title = "Index"; }<h2>頁面</h2> <h2>@ViewBag.User.Age</h2> <h2>@ViewBag.User.Name</h2>
?
4.TempData
4.1 TempData的信息在"一次網頁要求內有效"(ActionResult的返回類型必須為RedirectToRouteResult或RedirectToRouteResult類別,除此以外只要有取用的TempData的鍵值,默認就會在當次網頁就要求清除,但你只是單純設置了TempData的值,并沒有讀取行為的話,TempData還是會保留到下次使用)
public class TestController : Controller{public ActionResult Index(string msg){TempData["msg"] = msg;return RedirectToAction("Index2");}public ActionResult Index2(){return View();}}
?