码迷,mamicode.com
首页 > Web开发 > 详细

MVC 控制器之间传值学习——session

时间:2017-07-26 23:36:52      阅读:424      评论:0      收藏:0      [点我收藏+]

标签:get   今天   view   about   default   src   using   home   where   

刚接触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

  运行结果:

技术分享

 

技术分享

 

MVC 控制器之间传值学习——session

标签:get   今天   view   about   default   src   using   home   where   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!