Various ways to pass data from Controller to View in MVC

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.

Note: Click on an image to enlarge it.

ViewBag


ViewBag is 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.

Between Controller and View


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

Between View to View


In 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 the advantage of 'Model'.


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

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


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

ViewData

ViewBag and ViewData serves 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:


In above image, everything is normal instead something in 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, here you have all the freedom.

ViewData to ViewBag


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 use dynamics to access the data instead of using magic <strings> conversion, you can realize it by 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 recommend, however, that you actually use them interchangeably, since it will confuse others.

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

ViewModels

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


In the above image, we have multiple people in a list from being passed as a View, simple. I will add one more thing here, you are not going to get intellisence 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.


TempData

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.

Example1: Using TempData like 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:

Example2: 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";

            return new RedirectResult(@"~\Friend\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 above ‘FriendController’, I’m redirecting the view, means Index() view will be redirected to 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.


Please read this blog also http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx.

Hope this helps. Thanks.
Abhimanyu Kumar Vatsa

Comments

  1. Excelent Post Sir it has helped allot

    ReplyDelete
  2. I believe you have forgot one very basic and important scenario.

    How about passing data from View to controller?

    Consider I have
    Textbox - To take Input Name
    Label - To display output Name, which I have type in Textbox
    Button - Onclick of button display name taken in textbox to label.

    I want to know what is good/ideal way to deal with this situation. It is very easy when we are doing with webforms but not sure with MVC.

    ReplyDelete
    Replies
    1. not forgot friend, will cover in other post. MVC has great power, be tuned i'm coming with a new post soon that will describe all. thanks.

      Delete
  3. Thanks for the wonderful article. Makes things clear and easy to understand.

    ReplyDelete
  4. Thanks for sharing good information. really helps a lot

    ReplyDelete
  5. Awesome...........
    Plz be continue......

    ReplyDelete
  6. Very good article sir.
    Keep up the Good wok of guiding us..


    Thank you very Much.

    ReplyDelete
  7. Excellent work sir.....explained in a clear and crisp manner...thank you...

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System