MVC 控制器之間傳值學習——session

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.