ViewData in ASP.NET Core MVC

ViewData in ASP.NET Core MVC Application

In this article, I will discuss ASP.NET Core MVC ViewData with Examples. Please read our previous article before proceeding to this article, where we discussed ASP.NET Core MVC Views with Examples.

How do you Pass Data to Views in ASP.NET Core MVC?

In ASP.NET Core MVC Applications, we can pass the data from a controller action method to a view in many different ways, such as by using ViewBag, ViewData, TempData, and a Strongly Typed Model. In this article, I will show you how to use ViewData to pass the data from the controller action method to a view. The other three techniques, i.e., ViewBag, Tempdate, and Strongly Typed View Model, will be discussed in our upcoming articles.

What is ViewData in ASP.NET Core MVC Application?

ViewData in ASP.NET Core MVC is a dictionary object that allows you to pass data from a controller action method to a view. It’s a dynamic property of the ControllerBase class and is used to store data that is only needed for the duration of an HTTP request. This means it does not persist across subsequent requests.

Now, if you go to the definition of ViewData, then you will see that ViewData is defined as a property in the Controller abstract class, and its type is ViewDataDictionary. This property is also decorated with the ViewDataDictionary attribute, as shown in the image below. 

What is ViewData in ASP.NET Core MVC Application?

As you can see in the above image, the data type of ViewData Property is ViewDataDictionary. Let’s have a look at the definition of the ViewDataDictionary by right-clicking on it and selecting go to definition, and you will see the following definition.

ViewData in ASP.NET Core MVC

As you can see in the above image, the ViewDataDictionary class implements the IDictionary interface. So, the ViewData in ASP.NET Core MVC is a dictionary object. As it is a dictionary object, it will store the data in the form of Key-Value Pairs where each key must be a string, and the value that we pass to the dictionary will be stored as an object type. Here, the key is of type String, and the value is of type object, i.e., we can store any data, including null.

How do you use ViewData in the ASP.NET Core MVC Application?

To use ViewData in the ASP.NET Core MVC Application, we first need to create a new key in ViewData and then assign some data to it. The key should be in string format, and you can give any name to the key. Then, you can assign any data to this key, such as the following.
ViewData[“KeyName”] = “Some Data”;

Since ViewData is a server-side code, hence to use it on a view, we need to use the razor syntax, i.e., @ something as follows.
@ViewData[“KeyName”]

You can access the string data from the ViewData dictionary without casting the data to string type. But if you are accessing data other than the string type, you must explicitly cast the data to the type you expect.

Example to Understand How to Access String Data using ViewData in ASP.NET Core MVC

Accessing String Data using ViewData in ASP.NET Core MVC

Example to Understand How to Access Student Data using ViewData in ASP.NET Core MVC

Accessing Student Data using ViewData in ASP.NET Core MVC

Note: ViewData stores data in key-value pairs. The key is a string, and the value can be an object of any type. Since ViewData is a dynamic property, you can add any number of key-value pairs to it without defining a model class. This can be useful for passing small amounts of data to a view.

Example to Understand ViewData in ASP.NET Core MVC Application:

Let us see an example to understand how to use ViewData to pass data from a controller action method to a view using ASP.NET Core MVC Application. In our example, we want to pass three pieces of information from the controller action method to the view. One is the Page’s title, the second one is the page’s Header, and the third is the Student data we want to display on the page.

So, first, create an ASP.NET Core Web Application (with the name FirstCoreMVCWebApplication) with MVC (Model-View-Controller) Project Template, i.e., Creating ASP.NET Core Application using ASP.NET Core Web APP (Model-View-Controller) Template. Once you create the project, add a class file named Student.cs in the Models folder. Then, please copy and paste the code below into it.

namespace FirstCoreMVCWebApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string? Name { get; set; }
        public string? Branch { get; set; }
        public string? Section { get; set; }
        public string? Gender { get; set; }
    }
}
Modifying HomeController:

Next, modify the Home Controller class as shown below. Here, we remove the existing code and add one action method, i.e., Details. As part of this method, we create three ViewData objects to store the Title, Header, and Student data. Here, Title, Header, and Student are the keys of the ViewData Dictionary Object.

using Microsoft.AspNetCore.Mvc;
using FirstCoreMVCWebApplication.Models;

namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Details()
        {
            //String string Data
            ViewData["Title"] = "Student Details Page";
            ViewData["Header"] = "Student Details";

            Student student = new Student()
            {
                StudentId = 101,
                Name = "James",
                Branch = "CSE",
                Section = "A",
                Gender = "Male"
            };

            //storing Student Data
            ViewData["Student"] = student;

            return View();
        }
    }
}
Creating Details.cshtml View:

Our previous article discussed the different ways to create Views in ASP.NET Core MVC Applications. Let us add a view with the name Details.cshtml within the Home folder, which is present inside the Views folder, as shown below. Once you add the Details view, your Views folder structure should look as shown below.

Creating Details.cshtml View

Now open Details.cshtml file and then copy and paste the below code into it. As you can see in the code below, we directly access the string data from the ViewData without type casting. But while accessing the Student data from the ViewData, we are typecasting it to the appropriate Student type.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewData["Title"]</title>
</head>
<body>
    <h1>@ViewData["Header"]</h1>

    @{
        var student = ViewData["Student"] as FirstCoreMVCWebApplication.Models.Student;
    }

    <div>
        StudentId : @student?.StudentId
    </div>
    <div>
        Name : @student?.Name
    </div>
    <div>
        Branch : @student?.Branch
    </div>
    <div>
        Section : @student?.Section
    </div>
    <div>
        Gender : @student?.Gender
    </div>
</body>
</html>

Now run the application and navigate to the “/Home/Details” URL, and you will see the data as expected, as shown below.

ViewData in ASP.NET Core MVC

When to Use ViewData in ASP.NET Core MVC?

The following are some of the scenarios when you might use ViewData:

  • Passing Small Amounts of Data: ViewData is ideal for passing small amounts of data from the controller to the view. It’s not suitable for large, complex data structures.
  • Loosely Typed Data: Since ViewData requires typecasting and checks for null values, it’s best used when you don’t need strict typechecking. If you require strong typing, consider using ViewModel instead.
  • Temporary Data Transfer: It’s useful for transferring data that is only needed for the current request. ViewData values do not persist on redirects. If you need data persistence across redirects, TempData might be a better choice.
  • Non-Critical Information: Use ViewData for non-critical information that doesn’t affect the core functionality of your page. This is because typecasting errors can occur, leading to runtime errors.
  • Compatibility with Older ASP.NET MVC Applications: If you’re migrating an older ASP.NET MVC application that already uses ViewData, continuing to use it can simplify the migration process.
Advantages of ViewData in ASP.NET Core MVC
  • Dynamic: ViewData is a dictionary object that can hold any type of data. This flexibility allows you to pass different types of data to your view without defining a specific class or type.
  • Easy to Use: It is straightforward to implement. You just need to assign values in your controller and read them in your view.
  • Late Binding: Since it’s a dictionary, it supports late binding, which means you can add properties as needed without having to alter a predefined data model.
  • Compatibility: It works well in scenarios where you need to pass small amounts of data that don’t require a complex object model.
Disadvantages of ViewData in ASP.NET Core MVC
  • Type Safety: ViewData lacks type safety, which can lead to runtime errors if you accidentally pass the wrong type of data or misspell a key.
  • Limited Scope: It is only available for the current request. If you need to persist data across multiple requests, ViewData is not suitable.
  • No IntelliSense Support: Since it’s a dictionary and uses strings as keys, you won’t get IntelliSense support in Visual Studio, increasing the chance of typos and key mismatches.
  • Risk of Null Reference Exceptions: If you attempt to use a key that doesn’t exist in the ViewData, it could lead to null reference exceptions.
  • Maintenance Challenges: In larger applications, the usage of ViewData can become unwieldy and difficult to maintain, especially if there’s a lot of data passing between the controller and the view.

I will discuss ViewBag in ASP.NET Core MVC in the next article with Examples. In this article, I try to explain ViewData in ASP.NET Core MVC Application with Examples. I hope this article will help you to understand ASP.NET Core MVC ViewData.

6 thoughts on “ViewData in ASP.NET Core MVC”

  1. در ساخت VIEW برنامه این خطارا می دهد دلیل آن چیست؟
    There was an error running the Selected code generator ‘Package restore Rolling back package change for SampleMvcWeb’ .

Leave a Reply

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