1 Answers
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.
- public ActionResult StudentSummary()
- {
- var student = new Student()
- {
- Name = “Sandeep Singh Shekhawat”,
- Age = 24,
- City = “Jaipur”
- };
- ViewBag.Student = student;
- return View();
- }
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.
- @ {
- ViewBag.Title = “Student Summary”;
- var student = ViewBag.Student;
- }
- < table >
- < tr >
- < th > Name < /th> < th > Age < /th> < th > City < /th> < /tr> < tr >
- < td > @student.Name < /td> < td > @student.Age < /td> < td > @student.City < /td> < /tr>
- < /table>
Here we used one more thing, “ViewBag.Title”, that shows the title of the page.