淺談 MVC中的ViewData、ViewBag和TempData

來源:互聯網
上載者:User

標籤:[]   註冊   前台   provider   margin   mode   string   集合   target   

ViewBag和TempData的區別

ViewData ViewBag
它是Key/Value字典集合 它是dynamic類型對像
從Asp.net MVC 1 就有了 ASP.NET MVC3 才有
基於Asp.net 3.5 framework 基於Asp.net 4.0與.net framework
ViewData比ViewBag快 ViewBag比ViewData慢
在ViewPage中查詢資料時需要轉換合適的類型 在ViewPage中查詢資料時不需要類型轉換
有一些類型轉碼 可讀性更好

 

在控制器(Controller)中使用

ViewData:

       Controller裡取資料賦值

var markeType = new MarketDataProvider().GetBTIDData().Where(a=>a.ID!="0"); //在資料庫擷取資料,這是list資料      ViewBag.DateType = markeType;//給ViewBag.DateType 賦值  “DateType ”可以隨便寫名稱。

  *  前台調用

@foreach (var modelMarket in ViewData["Markettype"] as Dictionary<string, string>)                       {                              <div class="row" style="margin-top:10px">                                    <div class="col-md-4 text-right"><span class="red">*</span> @modelMarket.Value</div>                                </div>                        }

  

 

    ViewBag : 

      Controller裡取資料賦值

 

string str = "商標,著作權,交易,國際註冊";   string[] strs = str.Split(‘,‘); Dictionary<string, string> dic = new Dictionary<string, string>();            for(int i=0;i<5;i++)            {                dic.Add(i.ToString(),strs[i]);            }            ViewData["Markettype"] = dic;

  

      前台調用:

 

@foreach (var modelMarket2 in ViewBag.DateType)                    {                        <div class="row" style="margin-top:10px">                            <div class="col-md-4 text-right"><span class="red">*</span> @modelMarket2.Text</div>                        </div>                    }

    按F12運行網站便可以看到運行結果,兩個也可以用於不分頁的新聞列表。

TempData

TempData也是字典,所以它的使用完全等同於ViewData,但兩者之間還是存在很大的差異。

     TempData,顧名思義,就是臨時資料。TempData儲存在Session中,Controller每次請求的時候都會從Session中擷取TempData,然後清除Session。基於這樣的事實,在每次請求結束後,TempData的生命週期也就結束了。網上有一句話:TempData至多之只能通過一次Controller傳遞,假設我們的Controller是跳轉到下一個Controller,以此類推,在最後一個Controlle相應的視圖上,的確可以獲得該TempData。但是,這並不是說TempData已經跨請求傳遞了,這依然只是一次請求,至於是否是跨Controller傳遞,我認為不是,所謂的通過Controller傳遞,是指將TempData傳遞給View,在上面的例子中,只有最後的Controller才會將該TempData傳遞給View,所以,TempData的確是只能通過一次Controller傳遞。

註:有的文字內容搜自部落格園。

 

淺談 MVC中的ViewData、ViewBag和TempData

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.