Posted on 4/7/2020 11:17:38 AM by Admin

ViewData in MVC

ViewData:-

ViewData is a Dictionary object and is derived from ViewDataDictionary, so it stores data in key-value pair.

ViewData can only be used for passing data from controller to View and for a single request only.

Below are the points, we should know as a developer 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.