DEV Community

Anshu Verma
Anshu Verma

Posted on

Passing data from controller to the view

There are three ways to pass data to the view :-

1. View Data dictionary :-

Every controller has a property called ViewData which is of type ViewDataDictionary.

Image description

Image description

Problem with this approach:- **
**Typecasting :-
We can't access Name property of our Movie because each item in the dictionary is of type object so we need to explicitly cast it to the Movie.
No compile time safety/ Null Reference exception:- In controller, If we change the magic string from ViewData["Movie"] to ViewData["RandomMovie"], we have to remember to go back in the view and make this change here as well otherwise we will get a Non Reference Exception.

2. ViewBag :-

May have this View Data in very 1st version of MVC and then ViewBag comes into the picture which is dynamic type but it also has the same problems like typecasting/casting and no compile time safety. So honestly, I have no idea why to use ViewBag as an improvement for View Data. So please do not use ViewData or ViewBag. If you want to pass data to the view just use the third approach I.e "Passing Model object to the View"

3. By passing Model object to the View :-

Image description

Top comments (0)