ViewData in ASP.NET MVC

ViewData in ASP.NET MVC

ViewData in ASP.NET MVC Application

In this write-up, I will explain the usage of ViewData in an ASP.NET MVC application with practical examples. Before moving forward, I recommend reviewing our previous article, where we covered Models in the ASP.NET MVC application. In this article, we will go over the following key points related to MVC ViewData.

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 an ASP.NET MVC application, we have multiple ways to transfer model data from a controller to a view. These include ViewBag, ViewData, TempData, Session, and Application, along with the option of using strongly typed views. Additionally, Session and Application State variables can be utilized, similar to traditional Web Forms, to manage data either during a user session or across the entire application.

The key question that may arise is when to use ViewData, ViewBag, TempData, Session, and Application, as each comes with its own benefits and limitations. As we move forward in this course, you will gain a clear understanding of when to choose one over the other. In this article, I will demonstrate how to use ViewData to transfer data from a controller action method to a view.

What is ViewData in ASP.NET MVC?

In the ASP.NET MVC Framework, ViewData serves as a mechanism for passing data from a controller action method to a view. If you inspect the definition of ViewData by right-clicking on it and selecting "Go to Definition", you will notice that ViewData is a property within the ControllerBase class, and its type is ViewDataDictionary, as illustrated in the image below.

As shown in the image above, ViewData returns a type of ViewDataDictionary. Now, let’s examine the definition of the ViewDataDictionary class.

As you can see, the ViewDataDictionary class implements the IDictionary interface. This means that ViewData in the ASP.NET MVC Framework functions as a dictionary object. Since it is a dictionary, it stores data in key-value pairs, where each key must be a string, and the corresponding value is stored as an object type.

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

An important point to keep in mind is that since ViewData stores data as an object, type casting is necessary when retrieving the data. However, if you are accessing string data, explicit type casting is not required. For any data type other than string, you must explicitly cast ViewData to its actual type before using it.


ViewData in ASP.NET MVC with String Type:


ViewData in ASP.NET MVC with Complex Type:


Example of ViewData in ASP.NET MVC Application:

Let's go through an example to understand how ViewData can be used to transfer data from a controller action method to a view. Before proceeding, I recommend reviewing our previous article, as we will be building upon the same example. To start, let’s quickly recap what we covered earlier. First, we created the Employee Model, which is responsible for holding employee data in memory.


Next, we created the EmployeeBusinessLayer model to handle employee data management. In this model, we defined a method that accepts an employee ID as an input parameter and returns the corresponding employee details.For now, the employee data is hardcoded, but in an upcoming article, we will explore how to fetch employee information from a database such as SQL Server, MySQL, Oracle, and more.

Next, we created the EmployeeBusinessLayer model to handle employee data management. In this model, we defined a method that accepts an employee ID as an input parameter and returns the corresponding employee details. For now, the employee data is hardcoded, but in an upcoming article, we will explore how to fetch employee information from a database such as SQL Server, MySQL, Oracle, and more.


namespace FirstMVCDemo.Models
{
    public class EmployeeBusinessLayer
    {
        public Employee GetEmployeeDetails(int EmployeeId)
        {
            
            Employee employee = new Employee()
            {
                EmployeeId = EmployeeId,
                Name = "Arshiya",
                Address = "Aurangabad",
                City = "Mumbai",
                Gender = "Female",
               Salary = 1000
            };
            return employee;
        }
    }
}                

Next, we updated the Index action method in the HomeController, as shown below, to fetch employee data from the EmployeeBusinessLayer and store it in the Employee model.


Passing ViewData From a Controller Action Method to a View:

Now, let's explore how to use ViewData to pass the Employee object to the Index view. Additionally, we will also pass the page header using ViewData. To achieve this, update the Index action method in the HomeController 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 ASP.NET 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 all! Now, run the application, and you should see the employee details displayed on the webpage as intended.

ViewData in MVC is evaluated dynamically at runtime. This means it doesn’t offer compile-time error checking, and you won’t receive IntelliSense support. For instance, if you misspell a key name, there won’t be any compile-time error, and the issue will only be apparent at runtime.


ViewData in ASP.NET MVC can only pass data from a controller action method to a view. This means that it is only valid for the current request.


In the next article, I will discuss ViewBag in an ASP.NET MVC Application with examples. In this article, I’ve focused on explaining the usage of ViewData in an ASP.NET MVC Application. I hope this article on ViewData in MVC has been helpful for you. I would love to hear your thoughts! Please feel free to share your feedback, questions, or comments about this article.