Reputation: 4069
From what I've read, information placed into TempData will be there for the current request and the next request (so that you can pass information across redirects). The problem is that if I browse to a controller action that does not redirect, the information in TempData will still be there for the next request. I'm using TempData to store informational messages that are displayed to the user, so now I'm getting the messages for the first screen on the second screen also.
Is there a good time in the controller lifecycle to clear out TempData once it's not used anymore?
Upvotes: 6
Views: 11081
Reputation: 28153
I think you shoud use ViewData if you are not using POST-REDIRECT-GET. But if you really need the behavior you've described above you should create your own custom TempDataProvider:
public class YourTempDataProvider : SessionStateTempDataProvider
{
public override void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
{
bool redirecting = ...
if(redirecting)
{
base.SaveTempData(controllerContext, values);
}
}
}
Upvotes: 0
Reputation: 13679
I wouldn't look for a certain place here, other than a custom TempDataProvider. But that's tricky. What if you want the regular behavior in other controllers? I'd YAGNI this for now and just clear it out where you need it to be cleared out. As you notice a pattern you can pull it up to some common place.
Upvotes: 0
Reputation: 126547
Use ViewData instead of TempData if you are not redirecting. You should never need to clear TempData manually. If you only use it when redirecting, it will be cleared for you, automatically and at the correct time.
Upvotes: 7