MVC C# TempData
Asked Answered
I

3

20

Can somebody please explain the purpose of TempData in MVC. I understand it behaves like ViewBag but what does it do beyond that.

Illuminating answered 7/5, 2012 at 18:16 Comment(1)
Not sure where you got the idea it "behaves like ViewBag," because it does nothing of the sort.Luo
P
27

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. Therefore, the only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view. Looking back at the previous HomeController code sample means that the TempData object could yield results differently than expected because the next request origin can't be guaranteed. For example, the next request can originate from a completely different machine and browser instance.

http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

Plafker answered 7/5, 2012 at 19:32 Comment(0)
N
8

ViewBag

Allows you to create dynamic properties

Passing data between the controller and view

Controller

ViewBag.Name= "Lion";

View

<div>
  <h4>@ViewBag.Name</h4>
 </div>

TempData

TempData is meant to be a very short-lived instance

you should only use it during the current and the subsequent requests only

TempData dictionary is used to share data between controller actions

TempData["Name"] = "Lion";
Nickinickie answered 18/10, 2012 at 16:46 Comment(1)
I am afraid this answer actually does not answer the question at all. -1Dollie
I
2

TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

public TempDataDictionary TempData { get; set; }

It is a property of ControllerBase class.It is used to pass data from current request to subsequent request (means redirecting from one page to another). It’s life is very short and lies only till the target view is fully loaded. It’s required typecasting for getting data and check for null values to avoid error.It is used to store only one time messages like error messages, validation messages.

Inger answered 20/1, 2016 at 9:55 Comment(1)
the lack of info on this is annoying. How does Tempdata work within the HTTP protocol? is it a short lived cookie like Play's playframework.com/documentation/2.6.x/JavaSessionFlash Is it something that is stored in server side session object? if so, this means that if you have multiple Servers you might not get that TempData as it only exists on one of them, right?Petterson

© 2022 - 2024 — McMap. All rights reserved.