[RESOLVED]What is the difference between viewbag and temdata ?

i like to know that what is the difference between viewbag and temdata with practical example

i just picked a code snippet but could not understand the difference between viewbag and temdata.

viewbag related code

public ActionResult ViewBagDemo()
{
    ViewBag.Courses = _repository.GetCourses();
    ViewBag.Students = _repository.GetStudents();
    ViewBag.Faculties = _repository.GetFaculties();
    return View();
}  

tempdata related code

public ActionResult TempDataDemo()
{
    // TempData demo uses repository to get List<courses> only one time
    // for subsequent request to get List<courses> it will use TempData
    TempData["Courses"] = _repository.GetCourses();

    // This will keep Courses data untill next request is served
    TempData.Keep("Courses");
    return View();
}
TempData.Keep("Courses");
@*Iterating Course model using TempData["Courses"] *@
@foreach (var item in TempData["Courses"] 
	as List <MultipleModelDemo.Models.Course>)
{         
    <option>@item.CourseName </option>            
}

what is special about tempdata keep function() what it does ?

please guide me thanks.

Hello Mouu,

ViewBag

  • ViewBag is a dynamic property (dynamic keyword which is introduced in .net framework 4.0)
  • ViewBag  is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
  • ViewBag doesn’t require typecasting for complex data type.

TempData

  •   TempData is a dictionary derived from TempDataDictionary class and it is a string key and object value.
  •  TempData keep the information for the time of an HTTP Request. This mean pass data from one page to another.
  •  It’s required typecasting for complex data type and check for null values to avoid error.
  •  Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables.

http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem

Data in the ViewBag is destroyed when the request has finished.  Data in TempData is kept between requests but is destroyed when it is read.  The Keep method stops the data being data being destroyed allowing it to be requested again in future.

Hi!

<div>1. ViewBag
</div> <div>

  • ViewBag is a wrapper around ViewData which is use to pass data from Controller to View. This object is the feature of .Net 4.0.
  • ViewBag is a dynamic property which is don’t require any type of typecasting for complex data types.
  • ViewBag’s value become null if redirection occur because its life lies only during current request.

<div>2. TempData</div> <div>

  • TempData is a dictionary object that is derived from TempDataDictionary class which is used to pass data from current request to subsequent request in case of redirection.
  • TempData having the short lives session and lies only till the target view is fully loaded.
  • It requires type casting for complex data type. It is recommended to check for null values to avoid error. 

Hope it helps you to understand the difference between them. Let me know if any query remains.

Cheers

</div> </div>

U said viewbag data is flush when request is finished….what does it mean? Explain with sample scenario.

explain temp data is kept even after read.

TempData Represents a set of data that persists only from one request to the next.After next request is done the data is automatically flushed.A good example has been shown in below discussion , please check the same:

http://stackoverflow.com/questions/12815739/tempdata-wont-destroy-after-second-request

Viewbag on the other hand will get destroyed when one request if done.

mou_inn

U said viewbag data is flush when request is finished….what does it mean? Explain with sample scenario.

explain temp data is kept even after read.

About TempData

The TempData acts very similar to that of the Session, ViewBag or ViewData except that it is extremely temporary and will only persist through a single request. As a result of this, the TempData can be useful to pass values from one Controller Action to
another without having to use any more persistant forms of data transfer. Greg Shackles has an excellent blog post on "Everything You Need to Know about TempData" that
might be worth reading if you are so inclined.

It’s great for short-lived things like displaying validation errors or other small messages that you don’t need to persist for longer than a single request. You can see an example demonstrating this below :

public ActionResult BeforeSetting()
{
            // Check the ViewData and TempData
            TempData["Test"] = "Example";
            ViewBag.Test = "Example";
            return View();
}

public ActionResult AfterSetting()
{
            // Now attempt to access these same values in these areas
            var temp = TempData["Test"];
            var view = ViewBag.Test;

            return View();
}

Notice in the above example, in your BeforeSetting() action, you are setting both the TempData and the ViewBag with a value. Now we will make the BeforeSetting() View look something like the following (to automatically redirect to your other action) :

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>BeforeSetting</title>
    <script type="text/javascript">
        // Navigate automatically to your other action
        window.location.href = '@Url.Action("AfterSetting")';
    </script>
</head>
<body>
    <!-- Nothing -->
</body>
</html>

If you place a breakpoint within your AfterSetting action, you should see that the TempData value is persisted (since it hasn’t been accessed yet) however the ViewBag values are no longer available (since the original request they were set in has elasped)
:

Regarding When to Use One over the Other

The ViewBag and ViewData are predominately used to pass values from the Controller to the View (although they can be used outside of that) whereas you may more often see the TempData collection used during navigation between Controller Actions. 

There are quite a few informative posts and articles out there that discuss when to use each of these temporary storage options, which you might want to consider looking through and hopefully they will help you figure out what you are looking for :

thanks for answer. r u trying to say temp data persist like session if yes then how long tempdata persist ? what is the life time of temp data?

suppose in one action method i store something into tempdata and redirect to view and in view i populate UI from tempdata tempdata and when user click then i was directed to another action method and from there i could redirect to another view or another
controller. so i like to know can we get the data intact in tempdata? please explain.

thanks

please see my last question in this same thread and answer if you like please.

@SRoja if possible will you please discuss about the image what you pasted here…..i need to understand the flow of the image you pasted here. thanks

mou_inn

thanks for answer. r u trying to say temp data persist like session if yes then how long tempdata persist ? what is the life time of temp data?

suppose in one action method i store something into tempdata and redirect to view and in view i populate UI from tempdata tempdata and when user click then i was directed to another action method and from there i could redirect to another view or another
controller. so i like to know can we get the data intact in tempdata? please explain.

thanks

TempData is stored in the session, the difference between session and tempdata is that when you access a session variable it stays there, when you access a tempdata variable it is deleted when you access it.  So tempdata is persisted as long as the session
is, or until it is read.  If you want to read the data but have it not be deleted (ie have it behave like a session variable) then that is when you use Keep.

In your example above, when the UI is populated from TempData the data is gone, unless you use Keep.

Leave a Reply