ASP.NET MVC中ViewData、ViewBag和TempData

时间:2023-01-29 13:30:23

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"] = "";
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 = , 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 = , 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();
}
}