asp.net mvc中ViewData、ViewBag和TempData的详解

时间:2023-03-09 03:09:37
asp.net mvc中ViewData、ViewBag和TempData的详解

一、ViewData和ViewBag

1、ViewData和ViewBag都是从Action向View传递数据的方式,当然还有其他方式如向View传递Model。

2、ViewData页面查询数据时需要转换合适的类型(var std in ViewData["students"] as IList<Student>),ViewBag不需要,他们的使用方法如下:

  1)ViewBag:

    controller中定义ViewBag.name="Tom";

    view中@ViewBag.name

  2)ViewData:

    controller中定义ViewBag["name"]="Tom";

    view中如下   

<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{
<li>
@std.StudentName
</li>
}
</ul>

3、ViewData和ViewBag都是ControllerBase类的属性,ViewData类型是ViewDataDictionary(字典键值对结构),ViewBag类型是dynamic,如下图:

asp.net mvc中ViewData、ViewBag和TempData的详解

4、ViewData和ViewBag本质一样,在ViewData使用的key不能和ViewBag的key相同,否而回报运行时错误,

http://www.tutorialsteacher.com/mvc/viewbag-in-asp.net-mvc原句:Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.

http://www.tutorialsteacher.com/mvc/viewdata-in-asp.net-mvc原句:ViewData and ViewBag both use the same dictionary internally. So you cannot have ViewData Key matches with the property name of ViewBag, otherwise it will throw a runtime exception.

5、ViewBag和ViewData仅针对当前Action中有效,生命周期和view相同。

二、TempData


1、TempData类型是TempDataDictionary。

2、 TempData用于把数据从一个action方法传到另一个action方法,两个action可以不再同一个controller中如下代码:

public class HomeController : Controller
{
public ActionResult Index()
{
TempData["name"] = "Tom";
TempData["age"] = ;
return View();
} public ActionResult About()
{
string userName;
int userAge;
if(TempData.ContainsKey("name"]))
userName = TempData["name"].ToString(); if(TempData.ContainsKey("age"]))
userAge = int.Parse(TempData["age"].ToString()); return View();
}
}

3、TempData 在第二次请求后会被清空,第三次请求则获取不到,如下:

第一次请求http://localhost/Home/Index,设置TempData["name"]="Tom";

第二次请求http://localhost/Home/About,可以获取var name = TempData["name"];

第三次请求http://localhost/Home/Details,通过var name = TempData["name"];是获取不到值的。

可以在第二次请求中TempData.Keep();语句来记住TempData["name"],这样第三次就可以继续获取了。

4、TempData 是使用Session存储数据的。

参考文章:http://www.tutorialsteacher.com/mvc/asp.net-mvc-tutorials