ASP.NET CORE MVC ViewBag and ViewData

In this tutorial we will discuss how to pass data from the Controller to the view using ViewData and ViewBag. we will also discuss the difference between ViewData and ViewBag.

ViewData

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

public ViewDataDictionary ViewData { get; set; }

ViewData does not provide compile time error checking. For example, if you mis-spell the key names you wouldn’t get any compile time error. You 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 our example, we want to pass student information to the view from the controller and we already have data into the student object. As we discuss, ViewData is a dictionary object, so it will store the data in the form of key-value pairs where each key must be a string. So to assign data we need to give keys and key must be string and student object.

ViewData["StudentData"] = student;

In our view we need typecast object to Student class

@{
    var sudentdata = ViewData["StudentData"] as SampleProjectCore.Student;
}

Student Name: @sudentdata.Name

 

You can access the string data from the ViewData dictionary without casting the data to string type. lets example of passing string value title. Assign the string value ViewData

ViewData["PageTitle"] = "Student Information";

Accessing string value from ViewData in view.

@{
    var sudentdata = ViewData["StudentData"] as SampleProjectCore.Student;
}

@ViewData[“PageTitle”]

Student Name: @sudentdata.Name

 

ViewBag

ViewBag is another way of passing the data from controller to view. ViewBag is a dynamic property of the Controller base class.

public dynamic ViewBag { get; }

ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.

ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. Using ViewBag the above code can be rewritten as below.

Let us now pass student data using ViewBag and make changes in our code.

ViewBag.StudentData = student;

In view make changes to access student object from ViewBag

@{
    var sudentdata = ViewBag.StudentData;
}

Student Name: @sudentdata.Name

 

You can watch our video version of this tutorial with step by step explanation.