ASP.NET MVC - ViewBag
We have learned in the previous section that the model object is used to send data in a razor view. However, there may be some scenario where you want to send a small amount of temporary data to the view. So for this reason, MVC framework includes ViewBag.
ViewBag can be useful when you want to transfer temporary data (which is not included in model) from the controller to the view. The viewBag is a dynamic type property of ControllerBase class which is the base class of all the controllers.
The following figure illustrates the ViewBag.
You can assign any number of properties and values to ViewBag. If you assign the same property name multiple times to ViewBag, then it will only consider last value assigned to the property.
The following example demonstrates how to transfer data from controller to view using ViewBag.
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
IList<Student> studentList = new List<Student>() {
new Student(){ StudentID=1, StudentName="Steve", Age = 21 },
new Student(){ StudentID=2, StudentName="Bill", Age = 25 },
new Student(){ StudentID=3, StudentName="Ram", Age = 20 },
new Student(){ StudentID=4, StudentName="Ron", Age = 31 },
new Student(){ StudentID=5, StudentName="Rob", Age = 19 }
};
// GET: Student
public ActionResult Index()
{
ViewBag.TotalStudents = studentList.Count();
return View();
}
}
}
In the above example, we want to display the total number of students in a view for the demo. So, we have attached the TotalStudents property to the ViewBag and assigned the student count using studentList.Count()
.
Now, in the Index.cshtml view, you can access ViewBag.TotalStudents property and display all the student info as shown below.
Total Students: 5
ViewBag doesn't require typecasting while retriving values from it.
Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.
- ViewBag transfers data from the controller to the view, ideally temporary data which in not included in a model.
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
- You can assign any number of propertes and values to ViewBag
- The ViewBag's life only lasts during the current http request. ViewBag values will be null if redirection occurs.
- ViewBag is actually a wrapper around ViewData.