ViewBag
ViewBag is nothing but a wrapper around ViewData and can be considered as a syntactic sugar of ViewData. It is also used to pass data from the controller to the view over a single request.
The only difference is that ViewBag is an object of a Dynamic property and uses reflection internally. Below are some important points related to ViewBag:
- Type casting for complex type is not required.
- Checking for null is also not necessary.
- It also does boxing and unboxing, so unnecessary uses should be avoided.
- No IntelliSense.
Let's take the same example with the ViewBag.
i) First, let's take an example with a 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 a 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; }
}
public ActionResult Index()
{
Employee emp = new Employee();
emp.Id = 1;
emp.Name = "Michael";
emp.Age = 22;
Viewbag.Employee = emp;
return View();
}
@{
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 the Dynamic property and uses reflection internally.
One important point regarding ViewBag and ViewData is that both use the same Dictionary object, so if you are using both ViewBag and ViewData in the same place collectively, the key should always be unique, or the last used value will be assigned to both, and you might get an exception depending on the scenario as follows:
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 the same key (Employee) for both ViewBag and ViewData. As the ViewBag comes last, ViewData will be replaced by the ViewBag's value and will store the string name="Ram" instead of the Employee object. So, in the view, if I try to fetch the Employee object from ViewBag, I'll get the following error:
@using MVCExample.Models
@{
var emp = (Employee)ViewData["Employee"];
}
@emp.Id
@emp.Name
@emp.Age