티스토리 뷰

🌈 .NET MVC

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

ViewBag&ViewData VS TempData 차이점

1. TempData는 Controller 와 Controller 사이에서 정보 전달이 가능하다.

2. TempData의 정보를 한번 호출 하여 사용하면 이후에는 정보가 삭제되어 사용할 수 없다.(휘발성)

 

 

 

 

 

 

 

 

 

 

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함