Back End/🌈 .NET
ViewBag & ViewData vs TempData
James Wetzel
2022. 6. 14. 15:06
📌ViewBag
Gets the dynamic view data dictionary.
Property Value
Object
The dynamic view data dictionary.
// in Controller
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
// in View
<%: ViewBag.Name %>
<%: ViewBag.Age %>
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
<%: ViewBag.DateNow %>
📌ViewData
Gets or sets the dictionary for view data.
Property Value
ViewDataDictionary
The dictionary for the view data.
// in Controller
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewData["listColors"] = colors;
ViewData["dateNow"] = DateTime.Now;
ViewData["name"] = "Hajan";
ViewData["age"] = 25;
return View();
}
// in View
<%: ViewData["name"] %>
<%: ViewData["age"] %>
<% foreach (var color in ViewData["listColors"] as List<string>){ %>
<font color="<%: color %>"><%: color %></font>
<% } %>
<%: ViewData["dateNow"] %>
📌TempData
Gets or sets the dictionary for temporary data.
Property Value
TempDataDictionary
The dictionary for temporary data.
// in Controller
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
TempData["listColors"] = colors;
TempData["dateNow"] = DateTime.Now;
TempData["name"] = "Hajan";
TempData["age"] = 25;
return View();
}
// in View
<%: TempData["name"] %>
<%: TempData["age"] %>
<% foreach (var color in TempData["listColors"] as List<string>){ %>
<font color="<%: color %>"><%: color %></font>
<% } %>
<%: TempData["dateNow"] %>
📌ViewBag&ViewData VS TempData
1. TempData는 Controller 와 Controller 사이에서 정보 전달이 가능하다.
2. TempData의 정보를 한번 호출 하여 사용하면 이후에는 정보가 삭제되어 사용할 수 없다.(휘발성)
728x90
반응형