ViewBag in MVC

by Sachin Singh


Posted on Tuesday, 07 April 2020

Tags: What is viewbag in mvc how to use viewbag in mvc viewbag

ViewBag:-

ViewBag is nothing but a wrapper around ViewData and can be considered as a syntatic sugar of ViewData.It is also used to pass data from controller to view over a single request.

The only Difference is ViewBag is an object of Dynamic property and uses reflection internally.

Below are some important points related to ViewBag.
  1. Type casting for complex type is not required.
  2. Checking for null is also not necessary.
  3. It also does boxing and unboxing, so unnecessary uses should be avoided.
  4. No intellisence.

Let's Take the same example with viewbag.

i) First let's take example with primitive data type. Create an Action Method like below.


   public ActionResult Index()
     {
        int id = 1;
        ViewBag.Id = id;
        return View();
     }

Access the id value from ViewBag in your view like below.


        @ViewBag.Id

ii) Take an example of complex Type.
create a class with some properties like below.


     public class Employee
      {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
     }


  • Create one action method like below.

   public ActionResult Index()
   {
    Employee emp = new Employee();
    emp.Id = 1;
    emp.Name = "Michael";
    emp.Age = 22;
    Viewbag.Employee = emp;
    return View();
  }


  • Access the Employee object from ViewBag in your view Like below.

  @{
    var emp = ViewBag.Employee;
    }
   @emp.Id
   @emp.Name
   @emp.Age

Note:-Here i have not used Type casting as the ViewBag is an object of Dynamic property and uses reflection internally.

One important point regarding ViewBag and ViewData is, both uses the same dictionary object so if you are using both viewbag and viewdata in the same place collectively then the key should always be unique or the last used value will be assigned to both and you might get exception depending on scenario like below.


    public ActionResult Index()
    {
     Employee emp = new Employee();
     emp.Id = 1;
     emp.Name = "Michael";
     emp.Age = 22;
     ViewData["Employee"] = emp;
     string name = "Ram";
     ViewBag.Employee = name;
     return View();
   }

Here I have used same key (Employee) for both viewbag and viewdata,as the viewbag comes last so viewdata will be replaced by viewbag's value and will store the string name="Ram" instead of employee object ,so in the view if I will try to fetch employee object from viewbag i will get below error.


  @using MVCExample.Models
  @{
    var emp = (Employee)ViewData["Employee"];
    }
  @emp.Id
  @emp.Name
  @emp.Age

Error caused by same key
Error due to same key