Back to: ASP.NET Core Tutorials For Beginners and Professionals
ViewData in ASP.NET Core MVC Application
In this article, I will discuss ViewData in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing how to create an ASP.NET Core Web Application using the MVC (Model-View-Controller) Project Template.
Different Ways to Pass Data to Views in ASP.NET Core MVC
ASP.NET Core MVC is a robust framework for building web applications. One of the essential tasks in any MVC application is passing data from the Controller to the View. Since Views are responsible for rendering the UI, they need data to display meaningful content to users. ASP.NET Core MVC offers several techniques for passing data to Views effectively. In ASP.NET Core MVC, the following are the common ways to pass data from the Controller to the View:
- ViewData: A dictionary object that stores data as key-value pairs.
- ViewBag: A dynamic wrapper around ViewData, allowing property-like syntax.
- TempData: Used to pass data between two consecutive requests, such as during redirects.
- Strongly Typed Models/View Models: Passing a model object directly to the View.
- Session: Storing data in server-side session to be accessed in Views.
Each of these methods serves different purposes depending on the scenario, data lifetime, and type safety requirements.
What is ViewData in ASP.NET Core MVC?
ViewData is a dictionary object of type ViewDataDictionary that allows us to pass data from a Controller to a View using key-value pairs. ViewData is request-scoped, meaning the data it contains is only available during the current HTTP request. It is useful for passing small, non-complex pieces of information.
- It stores data as string keys and object values.
- It is accessible within both the Controller and the View.
- The data in ViewData only lasts for the duration of the current HTTP request.
If you go to the definition of ViewData, you will see that it is a property in the Controller base class, and its type is ViewDataDictionary. This property allows us to attach data to our controller, which is then available for use in the corresponding view. This property is also decorated with the ViewDataDictionary attribute, as shown in the image below.
As you can see in the above image, the data type of the ViewData Property is ViewDataDictionary. Let’s look at the definition of the ViewDataDictionary by right-clicking on it and selecting go to definition, and you will see the following definition.
As you can see in the image above, the ViewDataDictionary class implements the IDictionary<string, object?> interface. Since it stores data as objects, explicit type casting is required when retrieving data in the View.
So, ViewData in ASP.NET Core MVC is a dictionary object. As a dictionary object, it stores 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, i.e., we can store any data, including null.
How to use ViewData in an ASP.NET Core MVC Application?
Using ViewData is straightforward:
- In the Controller, assign data to the ViewData dictionary using a string key.
- In the View, retrieve the data by accessing the ViewData dictionary with the same key and casting it to the appropriate type.
How to Access String Data using ViewData in ASP.NET Core MVC?
You can access the string data from the ViewData dictionary without casting the data to the string type. The example is shown below:
How to Access Student Data using ViewData in ASP.NET Core MVC?
However, if you are accessing data other than the string type, you must explicitly cast the data to the type you expect. The example is shown below, where we access student data.
Example to Understand ViewData in ASP.NET Core MVC Application:
Let us see an example of using ViewData to pass data from a controller action method to a view. In this example, we will pass three different types of data from a Controller action to a View using ViewData:
- A page title (string)
- A page header (string)
- A Student object (complex model)
Step 1: Create the ASP.NET Core MVC Project
Start by creating a new ASP.NET Core Web Application using the MVC template:
- Project name: FirstCoreMVCWebApplication
- Choose ASP.NET Core Web App (Model-View-Controller) as the template
- This gives you the basic MVC structure: Models, Views, and Controllers folders
Step 2: Define the Student Model
Next, inside the Models folder, create a new class file named Student.cs and copy and paste the following code. This model represents a student entity with multiple properties.
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; } } }
Note: This class has properties like StudentId, Name, Branch, Section, and Gender. The nullable reference types (string?) allow these string properties to be null safely.
Step 3: Modify the HomeController
Open the HomeController.cs inside the Controllers folder and copy and paste the following code. Here, as part of the Details action method, we create three ViewData objects to store the Title, Header, and Student data.
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(); } } }
Code Explanation:
- ViewData is a dictionary accessible inside the Controller and View.
- We add three key-value pairs:
- “Title”: a string value for the page title.
- “Header”: a string for the page header.
- “Student”: the complex object containing student details.
- We return the View associated with this action (Details.cshtml by convention).
Step 4: Create the Details.cshtml View
Inside the Views/Home folder, add a new Razor view named Details.cshtml, and then copy and paste the following code. As you can see in the code below, we directly access the string data from the ViewData without casting it to a specific type. However, when accessing the Student data from the ViewData, we typecast 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>
Code Explanation:
- We use @ViewData[“Title”] and @ViewData[“Header”] directly to output the string values.
- To access the complex Student object, we cast ViewData[“Student”] back to the Student type using the as keyword.
- The null-conditional operator ?. ensures that if the student is null, it won’t throw an error, but will not render the property.
- We display each property of the student inside simple <div> elements.
Step 5: Run and Test the Application
Now, run the application and navigate to the “/Home/Details” URL. You will then see the data as expected, as shown below.
This confirms that:
- Simple string values were passed successfully via ViewData.
- The complex object was passed, cast, and accessed correctly in the View.
When to Use ViewData in ASP.NET Core MVC?
ViewData is ideal in the following situations:
- When you need to pass small pieces of data from the Controller to the View that don’t belong to your main model, such as status messages, page titles, or other metadata.
- When you want to quickly share data between a Controller and its View without creating a strongly typed model.
- When the data is temporary and relevant only for the current request, it won’t persist across multiple requests.
- When type safety is not a major concern, since data stored in ViewData must be explicitly cast to the correct type when accessed in the View.
- When you want to pass data to Views or Partial Views without the overhead of defining a dedicated model class.
However, for scenarios involving complex data or where maintainability and type safety are essential, using strongly typed Models is a better and more robust choice.
ASP.NET Core MVC provides flexible data passing techniques between Controllers and Views. Among them, ViewData provides a simple, dictionary-based method for sharing data within a single request. It’s ideal for passing small, loosely typed data quickly without creating complex models. Understanding when and how to use ViewData effectively helps build clean, scalable, and maintainable MVC applications in ASP.NET Core.
In the next article, I will discuss ViewBag in ASP.NET Core MVC with Examples. In this article, I will try to explain ViewData in ASP.NET Core MVC Applications with examples. I hope this article helps you understand ASP.NET Core MVC ViewData.
Registration Open – Microservices with ASP.NET Core Web API
Session Time: 6:30 AM – 8:00 AM IST
Advance your career with our expert-led, hands-on live training program. Get complete course details, the syllabus, registration, and Zoom credentials for demo sessions via the links below.
Typo ‘intelligence’ to be corrected as ‘intellisense’
Many Thanks , this article was really helpfull
How does the [ViewDataDictionary] decoration affect the ViewDataDictionary object?
Where is the ViewData object instantiated?
In ASP.NET Core MVC, the ViewData object is instantiated automatically by the MVC framework.
در ساخت VIEW برنامه این خطارا می دهد دلیل آن چیست؟
There was an error running the Selected code generator ‘Package restore Rolling back package change for SampleMvcWeb’ .
Kindly update your website:Please provide a next and previous buttons to redirect to next and previous pages.Its getting difficult to scroll up down and go through the details. Btw thanks a lot for efforts,most of the doubts are being clarified.
Please check that at the end of the article, we have Previous and Next Lesson buttons.