ViewData in MVC

by Sachin Singh


Posted on Tuesday, 07 April 2020

Tags: what is viewdata in mvc how to use viewdata in mvc

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 they could be retrieved by their key name.

ViewData can only be used for passing data from controller to view and it can persist value till a single request only, this means, the value you store in a 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 view, in a later article.

If you have ever worked on any .Net application using Visual Studio IDE then you must be knowing that how important it becomes to get IntelliSense to 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, it 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.

Following are some key points, you should remember, about ViewData
  1. Type Casting is necessary for complex Types.
  2. Need to check null values to avoid null value exception.
  3. Due to boxing and unboxing, it is not recommended to use ViewData unnecessarily.
  4. Due to no intellisense ,it is developer's work to remember the key name.

Let's take some example to make it more clear.

i) First let's take example with 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 use Type Casting as the value inside the viewdata was not of Complex type.

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;
    ViewData["Employee"] = emp;
    return View();
  }


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

  @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.