Back to: ASP.NET Core Tutorials For Beginners and Professionals
ViewData in ASP.NET Core MVC Application
In this article, I am going to 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 to 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 using 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?
In ASP.NET Core MVC, ViewData is a dictionary-like object that allows you to pass data from a controller action to its corresponding view. It’s part of the communication mechanism between the controller and the view.
The ViewData in ASP.NET Core MVC Application passes the data from the controller action method to a view. If you go to the definition of ViewData by right-clicking on it and selecting go to definition, then you will see that ViewData is defined as a property in the Controller abstract class, and its type is ViewDataDictionary, as well as this property, is decorated with ViewDataDictionary attribute as shown in the below image.
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.
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.
What is the use of ViewData in ASP.NET Core MVC Application?
- ViewData in ASP.NET Core MVC Application is used to pass the data from the controller action method to a view, and we can display this data on the view.
- The ViewData works on the principle of Key-Value pairs. This type of binding is known as loosely binding.
- Even though you can pass objects, we can pass any data in ViewData like a normal integer or string.
- ViewData uses the ViewDataDictionary type.
- Data is stored as an Object in ViewData.
- ViewData is available only for Current Request. It will be destroyed on redirection.
How to use ViewData in ASP.NET Core MVC Application?
In order to use ViewData in ASP.NET Core MVC Application, first, we 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, and then you can assign any data to this key something as follows.
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
Example to Understand How to Access Student Data using ViewData in ASP.NET Core MVC
Note: We can use n number of ViewData on a single view. ViewData can also be used to pass data from view to its layout 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 to the view from the controller action method. 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. And then, copy and paste the below code in 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 are creating 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.
Now open Details.cshtml file and then copy and paste the below code into it. As you can see in the below code, 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.
Points to Remember:
The ViewData is dynamically resolved at runtime; as a result, it does not provide any Compile Time Error checking, and we will not get any IntelliSense. For example, if we miss-spell the key names, then we wouldn’t get any compile-time error. We get to know about the error only at runtime.
The ViewData only transfers the data from the controller action method to a view, not vice versa. That means it is valid only during the current request.
A few important points to note about ViewData:
- Type Safety: ViewData is a dictionary of objects, so you must cast the values appropriately when retrieving them in the view. Incorrect casting can lead to runtime errors.
- Key Names: Keys used in ViewData are case-sensitive.
- Data Passing: ViewData is typically used to pass small amounts of data from the controller to the view for rendering purposes.
- Lifetime: The data stored in ViewData is available only for the duration of the current request-response cycle. It’s not meant for long-term data storage.
- Less Efficient than Strongly Typed Models: While ViewData provides flexibility, using strongly typed models (ViewModels) is often preferred because it provides better type safety and code clarity.
In modern ASP.NET Core MVC applications, using strongly typed models or ViewModels is generally considered a best practice. However, ViewData can still be useful for passing quick, small bits of data between controllers and views without the need to define a separate ViewModel class.
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.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
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?