What is the difference between Temp data, View, and View Bag?
Like ASP.net web forms in MVC we have also some way to keeping the data or passing the data from one request to another request or you can passing the data from one controller to another controller as well.
1. Temp data: It helps to maintain data when you pass data from one controller to other controller. Its a property of controllerbase class. Its life ended when the view is loaded completely. Mostly it is used to store validation messages. The life time can be managed by Keep() method.
2. View data: It helps to maintain data when you move from controller to view. Its a dictionary of objects. It takes a key as string like
ViewData["MyData"] = [Value you want to store]
Example:
ViewData["MyData"] = [Value you want to store]
Example:
- public ActionResult Index()
- {
- List<string> Teacher = new List<string>();
- Teacher .Add("John");
- Teacher .Add("Cleark");
- Teacher .Add("Pointing");
- ViewData["Teacher "] = Teacher ;
- return View();
- }
- //View code
- <ul>
- <% foreach (var teacher in ViewData["Teacher"] as List<string>)
- { %>
- <li><%: teacher %></li>
- <% } %>
- </ul>
3. View Bag: Both View Data and View Bag are used for same purposes. It’s a dynamic wrapper around view data.
ViewBag.[AnyProperty] = [Value you want to store]
Example:
We will discuss more on next Blog .Keep enjoying .
ViewBag.[AnyProperty] = [Value you want to store]
Example:
- public ActionResult Index()
- {
- List<string> Teacher= new List<string>();
- Teacher.Add("John");
- Teacher.Add("Cleark");
- Teacher.Add("Pointing");
- ViewBag.Teacher= Teacher;
- return View();
- }
- //Viewcode
- <ul>
- <% foreach (var teacher in ViewBag.Teacher)
- { %>
- <li><%: teacher%></li>
- <% } %>
- </ul>
We will discuss more on next Blog .Keep enjoying .
Comments
Post a Comment