ASP.NET MVC - ViewBag

The ViewBag in ASP.NET MVC is used to transfer temporary data (which is not included in the model) from the controller to the view.

Internally, it is a dynamic type property of the ControllerBase class which is the base class of the Controller class.

The following figure illustrates the ViewBag.

ViewBag Data Transfer

In the above figure, it attaches Name property to ViewBag with the dot notation and assigns a string value "Bill" to it in the controller. This can be accessed in the view like @ViewBag.Name.

You can assign a primitive or a complex type object as a value to ViewBag property.

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.

Note:
ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs.

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

Example: Set ViewBag in Action method
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. So, we have attached the TotalStudents property to the ViewBag and assigned studentList.Count() value.

Now, in the Index.cshtml view, you can access ViewBag.TotalStudents property, as shown below.

Index.cshtml
<label>Total Students:</label>  @ViewBag.TotalStudents
Output:
Total Students: 5

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 Limitations

  • ViewBag doesn't require typecasting while retrieving values from it. This can throw a run-time exception if the wrong method is used on the value.
  • ViewBag is a dynamic type and skips compile-time checking. So, ViewBag property names must match in controller and view while writing it manually.