
How to Pass Data From Controller to View in ASP.NET MVC
Sometimes when you are building a complex web application using ASP.NET MVC, you need to pass some critical information from your controller to your view. You can use your view models but maybe you just want to share a single value. You can’t create view models that just store single values. This is where ViewData, ViewBag, and TempData come in.
All three of the aforementioned techniques can be used to pass information from controller to your view without a hassle. Let’s take a look at simple examples of how they all work differently in various scenarios.
ViewData
Consider ViewData as a dictionary of objects. Whenever we extract data from ViewData, we need to cast it. How do you actually put data into ViewData and use it in your view? Let’s look at this example. Inside your controller, use the ViewData object to store values by providing key-value pairs.
And now you can use this value in your view like this.
The data is only accessible during the current request. Once you retrieve the data in the view from your controller, it becomes non-existent. ViewData is a really easy way to transfer data from a controller to view, but when dealing with abstract data types, you need to cast the values.
And in your view, you have to cast it like this:
ViewBag
ViewBag was introduced in MVC 3 and it behaves in the same way ViewData does. There are some subtle differences between the two. When using ViewBag, you don’t need to cast anything because ViewBag is just a dynamic wrapper around the dictionary that ViewData uses. ViewBag and ViewData point to the same dictionary and you can use either to get or put the values.
Let’s see how the above example changes when we use ViewBag instead of ViewData. This is how you put values inside ViewBag:
And below depicts how to extract data from ViewBag without casting.
Data stored in ViewBag also exists for the current request only. And because ViewBag and ViewData point to the same dictionary, you can put data from ViewData and retrieve it using ViewBag or vice versa.
TempData
TempData is mainly used when you want to redirect to another view or request with your stored data. Data stored in TempData exists for a single subsequent request and is very useful in situations to store data and redirect. Take a look at the example below.
You can use the ViewBag data like we did before.
After the redirect, TempData will become non-existent.
So, these are the basic differences between ViewData, ViewBag, TempData, and how to use them, We hope we made things clear for you and helped you understand how they are used.
Read Next: Is NoSQL Better Than SQL?