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:

  1. public ActionResult Index()  
  2. {  
  3.       List<string> Teacher = new List<string>();  
  4.       Teacher .Add("John");  
  5.       Teacher .Add("Cleark");  
  6.       Teacher .Add("Pointing");  
  7.    
  8.       ViewData["Teacher "] = Teacher ;  
  9.       return View();  
  10. }  
  11. //View code  
  12. <ul>  
  13.     <% foreach (var teacher in ViewData["Teacher"] as List<string>)  
  14.         { %>  
  15.     <li><%: teacher %></li>  
  16.     <% } %>  
  17. </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:
  1. public ActionResult Index()  
  2. {  
  3.       List<string> Teacher= new List<string>();  
  4.       Teacher.Add("John");  
  5.       Teacher.Add("Cleark");  
  6.       Teacher.Add("Pointing");  
  7.    
  8.       ViewBag.Teacher= Teacher;  
  9.       return View();  
  10. }   
  11. //Viewcode  
  12. <ul>  
  13.     <% foreach (var teacher in ViewBag.Teacher)  
  14.         { %>  
  15.     <li><%: teacher%></li>  
  16.     <% } %>  
  17. </ul>  

We will discuss more on next Blog .Keep enjoying .

Comments

Popular posts from this blog

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

The transaction is aborted or Failure while attempting to promote transaction.

Unable to load one or more breakpoints in Visual studio.