ViewData in ASP.NET MVC

ViewData in ASP.NET MVC Application

In this article, I am going to discuss the use of ViewData in ASP.NET MVC application with examples. Please read our previous article before proceeding to this article where we discussed Models in ASP.NET MVC application. As part of this article, we are going to discuss the following pointers.

  1. What is ViewData in ASP.NET MVC?
  2. How to Pass and Retrieve data From ViewData in ASP.NET MVC?
  3. Example of ViewData in ASP.NET MVC.

In ASP.NET MVC application, we can pass the model data from a controller to a view in many ways such as by using ViewBag, ViewData, TempData. You can also use the Session and Application State variable as we use in our traditional Web Forms to manage the data during a user session or throughout the application.

Now the most important question that comes to your mind is when to use ViewData, ViewBag, TempData, Session, and Application as each one having its own advantages and disadvantages. As we progress through this course you will come to know when to use one over another. Here in this article, I will demonstrate how to use the ViewData to pass the data from a controller to a view.

What is ViewData in ASP.NET MVC?

The ViewData in ASP.NET MVC is a mechanism to pass the data from a controller action method to a view. Let’s have a look at the signature of the ViewData.

signature of the ViewData in MVC

As you can see in the above image, the return type of ViewData is ViewDataDictionary. Let’s have a look at the definition of the ViewDataDictionary class.

Definition of ViewDataDictionary class in ASP.NET MVC

As you can see the ViewDataDictionary class implements the IDictionary interface. So we can say that the ViewData in ASP.NET MVC is a weakly typed dictionary object. As it is a dictionary object, so it is going to store the data in the form of key-value pairs where each key must be a string and the value that we are passing to the dictionary is going to be stored in the form of an object type

How to Pass and Retrieve data From ViewData in ASP.NET MVC?

The most important point that you need to remember is, as it stores the data in the form of an object so while retrieving the data from ViewData type casting is required. If you are accessing string data from the ViewData dictionary, then it is not required to typecast the ViewData to string type. But it is mandatory to typecast explicitly to the actual type if you are accessing data other than the string type from the ViewData.

ViewData in MVC with String Type:

ViewData in ASP.NET MVC with String values

ViewData in MVC with Complex Type:

ViewData in MVC with Complex Type:

Example of ViewData in ASP.NET MVC:

Let us see an example to understand how to use the ViewData dictionary to pass data from a controller to a view. Please read our previous article as we are going to work with the same example. Let us first recap of what we did in our previous article.

First, we create the following Employee Model to hold the employee data in memory.

Employee Model to hold the employee data in memory.

Then we created the following EmployeeBusinessLayer model to manage the employee data. Here we created one method which will take the employee id as input parameter and returns that employee information. As of now, we have hardcoded the employee data and in our upcoming article, we will discuss retrieving the employee data from a database like SQL Server.

EmployeeBusinessLayer model to manage the employee data

Then we modify the Index action method of Home Controller as shown below to retrieve the employee data from EmployeeBusinesslayer and store it in the Employee model.

Index action method of Home Controller

Passing ViewData From a Controller:

Now we will see, how to use the ViewData to pass the employee model to the Index view. Along with we are also going to pass the page Header using ViewData. So, modify the Index action method of the Home Controller class as shown below.

using FirstMVCDemo.Models;
using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeBusinessLayer employeeBL = new EmployeeBusinessLayer();
            Employee employee = employeeBL.GetEmployeeDetails(102);

            ViewData["Employee"] = employee;
            ViewData["Header"] = "Employee Details";

            return View();
        }
    }
}
Accessing ViewData in a View:

Now we will see how to access the ViewData within an MVC view. So, modify the Index Action method which is there within the Home folder in your application as shown below.

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Page Title</title>  
</head>
<body>
    @{
        var employee = ViewData["Employee"]
            as FirstMVCDemo.Models.Employee;
    }

    <h2>@ViewData["Header"]</h2>
    <table style="font-family:Arial">
        <tr>
            <td>Employee ID:</td>
            <td>@employee.EmployeeId </td>
        </tr>
        <tr>
            <td>Name:</td>
            <td>@employee.Name</td>
        </tr>
        <tr>
            <td>Gender:</td>
            <td>@employee.Gender</td>
        </tr>
        <tr>
            <td>City:</td>
            <td>@employee.City</td>
        </tr>
        <tr>
            <td>Salary:</td>
            <td>@employee.Salary</td>
        </tr>
        <tr>
            <td>Address:</td>
            <td>@employee.Address</td>
        </tr>
    </table>
</body>
</html>

That’s it. Now run the application and you will see the employee details in the webpage as expected.

The ViewData in ASP.NET MVC is resolved dynamically at runtime, as a result, it does not provide compile-time error checking as well as we do not get the intelligence support. For example, if we miss-spell the key names then we wouldn’t get any compile-time error rather we came to know the error at runtime.

The ViewData in ASP.NET MVC can only transfer the data from a controller action method to a view. That means it is valid only during the current request. 

In the next article, I am going to discuss the ViewBag in ASP.NET MVC Application with an example. Here, in this article, I try to explain the use of ViewData in ASP.NET MVC step by step with a simple example. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “ViewData in ASP.NET MVC”

  1. This completely is a nice tutorial. Thank you
    I’m having a doubt: after running the above program it is showing the same text as that of in the HTML page(no values). I’m using visual studio 2010. Is it because of the old version that razor is not taking?

Leave a Reply

Your email address will not be published. Required fields are marked *