ViewData, ViewBag, TempData, and viewdataviewbag in MVC
Differences between ViewBag and TempData
ViewData |
ViewBag |
It is a collection of Key/Value dictionaries. |
It is a dynamic type object. |
From Asp.net MVC 1. |
ASP. NET MVC3 |
Based on Asp.net 3.5 framework |
Based on Asp.net 4.0 and. net framework |
ViewData is faster than ViewBag |
ViewBag is slower than ViewData |
The appropriate data type needs to be converted when querying data in ViewPage. |
No type conversion is required when querying data in ViewPage. |
Some type conversion code |
Better readability |
Use in Controller
ViewData:
Assign values to data in Controller
Var markeType = new MarketDataProvider (). GetBTIDData (). Where (a => a. ID! = "0"); // obtain data from the database, which is list data ViewBag. DateType = markeType; // assign the value "DateType" to ViewBag. DateType and you can write the name as needed.
* Frontend call
@ Foreach (var modelMarket in ViewData ["Markettype"] as Dictionary <string, string>) {<div class = "row"> string str = "trademark, copyright, transaction, international Registration "; 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;
Foreground call:
@foreach (var modelMarket2 in ViewBag.DateType) { <div class="row">