3

My question simply is, how could the TempData be passed between Different controller? Naturally, because the controller contexts are different one controller should not be able to access the tempdata in another while tempdata can be simply passed between Action Results within the context of a single controller.

But let's say the situation necessitates cross controller communication OVER TempData, and TempData would be a requirement (regardless of whether it is a good practice or bad practice), is this possible ?

JAX
  • 1,540
  • 3
  • 15
  • 32

3 Answers3

2

Yes it is possible since TempData is backed by SessionState. It's essentially a special case of session state with a shorter lifespan.

Here is a similar question/answer Passing data between different controller action methods

Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135
  • Thanks for your fantastic straight forward answer TGH. Would add a little more details on how exactly it can be done like by providing an example. – JAX Nov 24 '14 at 03:56
  • 1
    Added a link that might help – TGH Nov 24 '14 at 03:58
  • it's not cross Controller, it explain passing between Actions inside a Controller. Lets say Controller X has an action that Redirects to an Action in Controller Y. Now if you use tempdata it will not be fetched by controlelr y – JAX Nov 24 '14 at 04:01
  • I haven't looked at this in a while, but my understanding of the answer here is that it addresses the two different controllers in the original question. From what I can tell tempdata should work in the case of a redirect. Failing that you could always just use regular session to do the job. – TGH Nov 24 '14 at 04:59
2

I was searching for this as well. In my case I did a ajax request, which inserted some data into temp data. Afterwards I would redirect with javascript to a different controller/action. After quit some searching I found out that in my case I had to call

TempData.Keep();

This will keep the temp data for the next request, despite the fact you don't use RedirectToAction

Maarten Kieft
  • 6,806
  • 3
  • 29
  • 34
0

TempData is a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. 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

For more information What is ViewData, ViewBag and TempData?

M.Azad
  • 3,673
  • 8
  • 47
  • 77