ViewData
ViewData is a Dictionary object and is derived from ViewDataDictionary, so it stores data in key-value pairs. Dictionary in C# is a collection that stores information in a key-value pair so that it can be retrieved by its key name.
ViewData can only be used for passing data from the controller to the view, and it can persist the value for a single request only. This means the value you store in ViewData becomes null after the very first request, as soon as the value is read in the View.
In reality, we rarely use ViewData or ViewBag in our application until it is highly required. We often use models. You will learn about strongly typed views, where we pass models from the controller to the View, in a later article.
If you have ever worked on any .NET application using Visual Studio IDE, you must know how important it is to get IntelliSense support in our application. For example, as soon as we create an object of a class and put a dot, Visual Studio starts showing all the methods and members it has. This makes our life easier, and there is less chance of error, but ViewData will not give you any IntelliSense. This means you will have to look back and remember the key name to get values back from ViewData.
The following are some key points you should remember about ViewData:
- Type Casting is necessary for complex Types.
- Need to check null values to avoid null value exception.
- Due to boxing and unboxing, it is not recommended to use ViewData unnecessarily.
- Due to no intellisense, it is the developer's work to remember the key name.
Let's take an example to make it clearer.
i) First, let's take an example with a primitive data type. Create an Action Method like below.
public ActionResult Index()
{
int id = 1;
ViewData["Id"] = id;
return View();
}
Access the id value from ViewData in your view like below:
@ViewData["Id"]
Note: Here, I haven't used Type Casting as the value inside the ViewData was not of a complex type.
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;
ViewData["Employee"] = emp;
return View();
}
@using MVCExample.Models
@{
var emp = (Employee)ViewData["Employee"];
}
@if(emp!=null)
{
@emp.Id
@emp.Name
@emp.Age
}
Note: Here, I have used Type Casting as the ViewData is storing a complex type.