MVC C# TempData

Nate Pet picture Nate Pet · May 7, 2012 · Viewed 38.6k times · Source

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

Answer

Jakub Konecki picture Jakub Konecki · May 7, 2012

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