ASP.NET MVC : Preserve TempData across multiple requests

user113003 picture user113003 · May 27, 2009 · Viewed 7.5k times · Source

There are values I need to pass when I perform redirects. I want to use TempData to accomplish this, but have encountered an issue.

I use a special controller to generate dynamic JavaScripts. For example, there might be a script tag like this:

<script type="text/javascript" src="/Resource/Script/Login.js"></script>

...but there is no script file "Login.js." Instead, the Script action of the ResourceController is being called:

public class ResourceController : Controller {
    public ActionResult Script(string id) {
        // set script = some code
        return JavaScript(script);
    }
}

The problem is, this eats up the next request, meaning that I can't use TempData to redirect from a page with a dynamic script. Is there any way the script action (or the ResourceController as a whole) can choose not to consume the TempData, allowing it to be available for the next "real" request?

Thank you in advance!

Answer

Tormod Hystad picture Tormod Hystad · May 25, 2011

The Asp.Net team removed this pain in MVC 2, by introducing TempData.Keep(), which makes sure all TempData items are tagged to live for one more request. Call this from all actions you want not to eat TempData.

Read the rationale behind introducing Keep() in Jacques Eloffs blog post

Keep() in MSDN docs