1、Viewbag
base.ViewBag.user1 = "张三";
@ViewBag.user1
2、ViewData
base.ViewData["user2"] = "李四";
@.ViewData["user2"]
3、session
base. HttpContext.Session["usr3"] = "王五";
@HttpContext.Current.Session["usr3"]
4、TempData
base.TempData["user4"] = "王六";
@TempData["user4"]
5、传对象( ViewData.Model)
student stu = new student(12, "789");
ViewData.Model= stu;
@model mvc.Models.student
<h3>@ViewData.Model.name</h3>
**注意:页面强类型,操作的成员变量必须被public修饰,否则不行**
6、传集合
List<Person> list1 = new List<Person>()
{
new Person {name="weijuan",age=26 },
new Person { name="bingbing",age=27},
new Person { name="tutu",age=10}
};
ViewData.Model = list1;
@model List<WebApplication2.Models.Person>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
@foreach (var item in Modedl) {
<tr>
<td>@item.name</td>
<td>@item.age</td>
</tr>
}
</tbody>
</table>
7、区别:当使用(Redirect)重定向的时候,ViewBage、ViewData 、ViewData.Model的值会发生丢失, base. HttpContext.Session、 base.TempData的值不会发生丢失
public ActionResult Index()
{
base.ViewBag.user1 = "张三";
base.ViewData["user2"] = "李四";
base. HttpContext.Session["usr3"] = "王五";
base.TempData["user4"] = "王六";
string name = "王七";
ViewData.Model = name;
return Redirect("/home/ToIndex");
}
public ActionResult ToIndex() {
return View();
}
<h1>@ViewBag.user1</h1>
<h1>@ViewData["user2"]</h1>
<h1>@HttpContext.Current.Session["usr3"]</h1>
<h1>@TempData["user4"]</h1>
<h1>@ViewData.Model</h1>
王五
王六
|