tags:

views:

381

answers:

3

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?

+3  A: 

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.

Craig Stuntz
But what if my controller action _is_ redirecting? I can't use ViewData in that case because the messages aren't there anymore.Is there a better way to deal with display messages like this than storing it in TempData/ViewData?
Jon Kruger
You need to use ViewData when not redirecting and TempData when you are redirecting. In both cases everything else is automatic. To display you then writeTempData["key"] ?? ViewData["key"] in your view.
Craig Stuntz
A: 

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);
        }
    }
}
eu-ge-ne
A: 

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.

Matt Hinze