刚接触MVC不久,写的一些代码自己都不忍心看下去。路漫漫其修远兮,宝宝还需努力!之前只用过Session做登录时用户信息的储存,今天对集合类数据做了小小的尝试:利用session在控制器之间传值,以减少代重复率。
1.将数据储存到Session中(不受类型限制);
2.从session中读取数据(注意转换为正确的的数据类型);
3.随你怎么操作。
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace TempDataStudy.Controllers {
//定义一个实体类 public class Stu { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class HomeController : Controller { public ActionResult Index() { List<Stu> Student = new List<Stu> { new Stu{Id=1,Name="张思宁",Age=22}, new Stu{Id=2,Name="习1近平",Age=24}, new Stu{Id=3,Name="江1泽民",Age=20} }; ViewBag.Student = Student;//向视图传值
Session.Remove("Stu");//移除Session["Stu"]
Session["Stu"] = Student;//向控制器About传值 return View(); } public ActionResult About(int id) { var Student = Session["Stu"] as List<Stu>;//获取存储在Session中的值 ViewBag.StuInfo = Student.Where(p => p.Id == id).FirstOrDefault(); return View(); } } }
@{
ViewBag.Title = "Home Page";
}
<table class="table table-hover">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Student)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@Html.ActionLink("详情", "About",new { id = item.Id })</td>
</tr>
}
</tbody>
</table>
@{
ViewBag.Title = "About";
var t = ViewBag.StuInfo;
}
序号:@t.Id
姓名:@t.Name
年龄:@t.Age
运行结果:


原文:http://www.cnblogs.com/fuxuyang/p/7242395.html