Home / ASP.NET - MVC / ViewBag

ViewBag in MVC ASP.NET

Is a DynamicViewData object, it is a ViewData wrapper class to allow flexible access to the object. ViewBag also allows us to use dynamic properties (using dots instead of square brackets like ViewData). Using ViewBag is similar to ViewData but more convenient because it doesn't require casting.

The following example demonstrates how to pass data from controller to view using ViewBag.

namespace MVC_BasicTutorials.Controllers
{
    public class StudentController : Controller
    {
        IList studentList = new List() { 
                    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 ActionResultIndex()
        {
            ViewBag.TotalStudents = studentList.Count();

            return View();
        }

    }
}

In the above example, we want to display the total number of students in the view. So assigned the number of students using ViewBag.TotalStudents = studentList.Count().
Now, in the Index.cshtml view, you can access the ViewBag.TotalStudents property and display the total number of students as shown below.

 @ViewBag.TotalStudents

Result:

Total Students: 5

ViewBag does not require casting while retrieving values.

ViewBag is a wrapper class around ViewData. It will throw a runtime exception, if the ViewBag property name matches the key of ViewData.

Points to remember :

  1. ViewBag passes controller data to the view, temporary data not contained in the model.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. You can assign any number of properties and values to ViewBag
  4. ViewBag's lifecycle during an active request. The value of ViewBag value will be null if a redirect occurs.
  5. ViewBag is actually a wrapper around ViewData.

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖