一、Control往View传递值
1.1 ViewBag
唯一识别。
他们的Key是共用的,如ViewBag.name其实和ViewData["name"]源代码是一样的,
ViewData和ViewBag中的值可以互相访问。
代码:
Control端:
public ActionResult Index2()
{
ViewBag.name = "张三";
ViewData["name"] = "李四";
return View();
}
View端:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2</title>
</head>
<body>
<div>
<span>ViewBag: 姓名:@ViewBag.name</span>
<span>ViewData: 姓名:@ViewData["name"]</span>
</div>
</body>
</html>
结果:
ViewBag: 姓名:李四 ViewData: 姓名:李四
1.2 ViewData
ViewData它key/Value的键值对。
Control端:
ViewData["name"] = "张三";
View端:
<span>年龄:@TempData["age"]</span>
主要区别:ViewPage查询数据的时候,ViewData需要做数据类型的转换(必须显式转换),而ViewBag不需要做一些数据类型的转换(隐式转换)。
Control端:
public ActionResult Index()
{
Student stu = new Student();
stu.name = "张三";
stu.age = 20;
ViewBag.student = stu;
ViewData["student"] = stu;
return View();
}
View端:
@{
ViewBag.Title = "Index";
}
<span>姓名:@ViewBag.student.name</span> <span>年龄:@ViewBag.student.age</span>
@{
var stu = @ViewData["student"] as @MVC传值.Models.Student;
}
<span>姓名:@stu.name</span> <span>年龄:@stu.age</span>
<a href="JumpMethod" >跳转到Test1View</a>
1.3 TempData
TempData只保存到下一个请求中,下一个请求完了之后,TempData就会被删除了。
TempData每一项即每一个Key对应的项次只能被(View或者Controller)使用一次,就会被销毁。
Request的定义从宏观上看就是页面刷新了一次。
Control端:
public ActionResult Index()
{
TempData["age"] = 20;
return View();
}
public ActionResult JumpMethod()
{
//TempData["age"] = 21;
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
return View();
}
View端:
1 <span>姓名: @ViewBag.name</span> <span>年龄:@TempData["age"]</span>