Back to: ASP.NET Core Tutorials For Beginners and Professionals
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 discussing How to Create an ASP.NET Core Web Application using the MVC (Model-View-Controller) Project Template.
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 is a dictionary object in ASP.NET Core MVC that allows us to pass data from a controller action method to a view. It provides a flexible way to pass data, allowing us to use key-value pairs. ViewData is useful when we need to pass dynamic data or data that doesn’t fit well into a strongly typed model. If you go to the definition of ViewData, you will see that It is 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.
As you can see in the above image, the data type of 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 above image, the ViewDataDictionary class implements the IDictionary. 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. 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 need to set the data in a controller by adding entries to the ViewData dictionary with a string key and then assign some data. 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.
How to Access String Data using ViewData in ASP.NET Core MVC
How to Access Student Data using ViewData in ASP.NET Core MVC
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 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 is the page’s Header, and the third is the Student data.
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:
In our previous article, we discussed the different ways to create Views in ASP.NET Core MVC Applications. Let us add a view named Details.cshtml within the Home folder, which is inside the Views folder, as shown below. Once you add the Details view, your Views folder structure should look as shown below.
Now open the Details.cshtml view and copy and paste the following code. As you can see in the code below, we directly access the string data from the ViewData without type casting. However, while 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>
Now run the application and navigate to the “/Home/Details” URL. As shown below, you will see the data as expected.
Features of ViewData in ASP.NET Core MVC:
- Type Safety: ViewData does not provide type safety as it stores data as an object. You need to cast the data to the appropriate type when retrieving it.
- Scope: The data in ViewData only lasts for the duration of the current HTTP request. It’s reset for each new request, so it is not a mechanism for persisting data between requests, such as across redirects.
- Accessing Data: You can set data in a controller by adding entries to the ViewData dictionary with a string key. In the view, you can access these values using the same key. When used in the view, the values must be cast to the appropriate type.
- Null Handling: ViewData returns null if a key does not exist, so you should check for null or use the ?. operator to avoid exceptions.
- Usage: ViewData is best used to pass small amounts of data. If you’re passing complex data or require type safety, consider using ViewBag or strongly typed views.
- Lightweight: ViewData is lightweight because it’s just a dictionary and doesn’t require any extra classes or interfaces.
- Dynamic: ViewData is a dynamic object, so you can use it to pass any data.
So, we need to use ViewData when we need to pass simple or small amounts of data that don’t justify creating a view model or when the data is temporary and used only within the view being rendered.
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 Application with examples. I hope this article will help you to understand ASP.NET Core MVC ViewData.
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.