剛接觸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
運行結果: