Various Ways to Pass Data From Controller to View in MVC

Introduction

There are various ways to pass data from a Controller to a View. I'm going to discuss how Controllers interact with Views and specifically cover ways you can pass data from a Controller to a View to render a response back to a client. So, let's get started.

ViewBag in MVC

ViewBag is a very well-known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary. Let's see how it is used.

Pass Data Between the Controller and View

ViewBag

In the above image, you can see how data flows from the "Controller" to the "View" and how it looks in the browser.

Pass Data Between View to View

ViewTitle

In the above image, you see how data is initialized on the "View" page itself using 'ViewBag.Title = "Index"' and then how it is getting rendered using '@ViewBag.Title'. What is "Title"? It is nothing more than a key, which has very limited availability and can be used on the same page only. So, the key naming is up to you; use any name which makes you happy.

Look at one more case, where I will take advantage of "Model".

Friend List

In the above case, we have a "Model" defined by the name "Friend" that has three properties "Id", "Name," and "Address". On the "Controller", we have an object of the "Friend" class named "find," and then, using the dot (.) operation, properties are assigned then attached to these properties of the ViewBag.

Look at one more example in which a list of students is passed using ViewBag.

Friend Controller

So, in this way, we can pass the list of students. I hope this is clear to you.

ViewData in MVC

ViewBag and ViewData serve the same purpose in allowing developers to pass data from controllers to views. When you put objects in either one, those objects become accessible in the view. Let's look at one example:

ViewData

In the above image, everything is normal instead of something in a foreach loop. ViewData is typed as a dictionary containing "objects"; we need to cast ViewData["Students"] to a List<string> or an IEnumerable<string> in order to use the foreach statement on it. Such as in.

@foreach (var std in (List<string>)ViewData["Students"])
//OR
@foreach (var std in (IEnumerable<string>)ViewData["Students"])

Now look at one more beauty of MVC, you can put data into the ViewBag and access it from ViewData or put data in the ViewData and access it from the ViewBag. You have all the freedom.

Pass Data ViewData to ViewBag

PassData

Pass Data ViewBag to ViewData

Viewbag to ViewData

So these two (ViewBag and ViewData) things seem to work almost exactly the same. Then, what's the difference? The difference is only how you access the data. ViewBag is actually just a wrapper around the ViewData object, and its whole purpose is to let you access the data dynamically instead of using magic <strings> conversion; you can realize it by the above examples. Some people prefer one style over the other. You can pick whichever makes you happy. In fact, because they're the same data just with two different ways of accessing it, you can use them interchangeably, like ViewData to ViewBag or ViewBag to ViewData. It is not recommended, however, that you actually use them interchangeably since it will confuse others.

Now, so far, we have looked into some ViewBag and ViewData, which are really very useful, but we can pass the data using a model also, and this will provide you with full intellisense features.

ViewModel in MVC

Using ViewModel, we can also pass the data from the Controller to View; let's look at the image.

ViewModel

In the above image, we have multiple people in a list form being passed as a View, simple. I will add one more thing here, you are not going to get IntelliSense support or a strongly typed view page here. To get it do it this way. Just add a reference of the model by using the IEnumerable interface, and you are done.

Enumerable

TempData in MVC

TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only. Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this. You can use TempData to pass error messages or something similar.

Example 1. Using TempData like a ViewData and ViewBag.

public class FriendController : Controller
{
    // GET: /Friend/
    public ActionResult Index()
    {
        ViewData["VDFriend"] = "Deepak K Gupta";
        ViewBag.VBFriend = "Deepak K Gupta";
        TempData["TDFriend"] = "Deepak K Gupta";
        return View();
    }
}

And on "View",

<p>Using ViewData: @ViewData["VDFriend"]</p>
<p>Using ViewBag: @ViewBag.VBFriend</p>
<p>Using TempData: @TempData["TDFriend"]</p>

This is a simple example, but we are not using the real advantage of TempData. Let's look at one more example.

Example 2. Using TempData to get data after redirect also.

public class FriendController : Controller
{
    // GET: /Friend/
    public ActionResult Index()
    {
        ViewData["VDFriend"] = "Deepak K Gupta";
        ViewBag.VBFriend = "Deepak K Gupta";
        TempData["TDFriend"] = "Deepak K Gupta";

        // Redirect to AnotherPage action
        return RedirectToAction("AnotherPage");
    }

    public ActionResult AnotherPage()
    {
        return View();
    }
}

And on "View".

<p>Using ViewData: @ViewData["VDFriend"]</p>
<p>Using ViewBag: @ViewBag.VBFriend</p>
<p>Using TempData: @TempData["TDFriend"]</p>

As in the above "FriendController", I'm redirecting the view. In other words, the Index() view will be redirected to the AnotherPage() view instantly, and now on another view, after one redirect, we won't be able to get data from ViewData or ViewBag, but TempData will work here.

Final Output


Similar Articles