ViewData in ASP.NET Core MVC

ViewData in ASP.NET Core MVC Application

In this article, I am going to discuss the use of ViewData in ASP.NET Core MVC application with examples. Please read our previous article before proceeding to this article where we discussed Views in ASP.NET Core MVC application.

In ASP.NET Core MVC application, we can pass the data from a controller action method to a view in many different ways such as by using ViewBag, ViewData, 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 rest techniques i.e. ViewBag, and strongly typed model are going to be discussed in our upcoming articles.

What is ViewData in ASP.NET Core MVC Application?

The ViewData in ASP.NET Core MVC is a dictionary of weakly typed objects which is derived from the ViewDataDictionary class.

What is ViewData in ASP.NET Core MVC Application?

Now, look at the definition of ViewDataDictionary as shown below.

What is the use of ViewData in ASP.NET Core MVC Application?

As you can see in the above image, the ViewDataDictionary implements ICollection, IEnumerable, and IDictionary interfaces where it will store the data in the form of key-value pairs. Here, the key is of type String and the value is of type object i.e. we can store any type of data.

What is the use of ViewData?
  1. ViewData is used to pass the data from the controller action method to a view and we can display this data on the view.
  2. The ViewData is work on the principle of Key-value pairs. This type of binding is known as loosely binding.
  3. We can pass any type of data in ViewData like normal integer, string, even though you can pass objects.
  4. ViewData uses the ViewDataDictionary type.
How to use ViewData?

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 it and then you can assign any data to this key.

ViewData[“KeyName”] = “Some Data”;

Since ViewData is a server-side code, hence to use it on view, we need to use the razor syntax i.e. @

@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 then you need to explicitly cast the data to the type you are expecting.

Example: Accessing string data

Accessing String Data from ViewData in ASP.NET Core MVC

Example: Accessing Student Data:

Accessing Object Data from 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.

ViewData Example 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. In our example, we want to pass three pieces of information to the view from the controller action method. One is the Title of the page, the second is the Header of the Page and the third one is the Student data that we want to display on the page.

First, create an ASP.NET Core Web Application with MVC (Model-View-Controller) project template. Once you create the project then add a class file with the name Student.cs in the Models folder. And then copy and paste the below code in it.

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

Now, modify the Home Controller class as shown below. Here, we are removing the existing code and adding one action method i.e. Details.

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 = "STD101",
                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 Application. Let us add a view with the name Details.cshtml within the Home Folder which is present inside the View Folder as shown below.

ViewData Example in ASP.NET Core MVC Application

Now open Details.cshtml and then copy and paste the below code in it. As you can see in the below code, we directly access the string data from the ViewData without typecasting. But while accessing the Student data from the ViewData, we are typecasting it to the appropriate 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

Points to Remember:

The ViewData is dynamically resolved at runtime, as a result, it does not provide any compiles time error checking as well as we do not get any intelligence. 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, but not vice-versa. That means it is valid only during the current request.

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

1 thought on “ViewData in ASP.NET Core MVC”

Leave a Reply

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