How to use ViewBag?

Category: C SharpHow to use ViewBag?
Editor">Editor Staff asked 2 years ago

How to use ViewBag?

1 Answers
Editor">Editor Staff answered 2 years ago

ViewBag is dynamic property that takes advantage of new dynamic features in C# 4.0. It’s also used to pass data from a controller to a view. In short, The ViewBag property is simply a wrapper around the ViewData that exposes the ViewData dictionary as a dynamic object. Now create an action method “StudentSummary” in the “DisplayDataController” controller that stores a Student class object in ViewBag.

 

  1. public ActionResult StudentSummary()  
  2. {  
  3.     var student = new Student()  
  4.     {  
  5.         Name = “Sandeep Singh Shekhawat”,  
  6.             Age = 24,  
  7.             City = “Jaipur”  
  8.     };  
  9.     ViewBag.Student = student;  
  10.     return View();  
  11. }  

Thereafter create a view StudentSummary (“StudentSummary.cshtml”) that shows student object data. ViewBag does not require typecasting for complex data type so you can directly access the data from ViewBag.

 

  1. @ {  
  2.     ViewBag.Title = “Student Summary”;  
  3.     var student = ViewBag.Student;  
  4. }   
  5. < table >  
  6.     < tr >  
  7.     < th > Name < /th> < th > Age < /th> < th > City < /th> < /tr> < tr >  
  8.     < td > @student.Name < /td> < td > @student.Age < /td> < td > @student.City < /td> < /tr>   
  9. < /table>  

Here we used one more thing, “ViewBag.Title”, that shows the title of the page.