views:

1827

answers:

4

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!

+3  A: 

Session is preserved between multiple requests.

Darin Dimitrov
Agreed - you're missing the point of TempData if you want it to do that
joshcomley
+5  A: 

You could place the line

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

after using TempData in view.

This article could also be useful for you: ASP.NET MVC TempData Is Really RedirectData

Alexander Prokofyev
I'd definitely recommend that article too!
joshcomley
that article is useful
aleemb
+2  A: 

Have your controller supertype override ExecuteCore, which clears TempData. I'm not saying this is a good idea...

protected override void ExecuteCore()
{
 string actionName = RouteData.GetRequiredString("action");
 if (!ActionInvoker.InvokeAction(ControllerContext, actionName))
 {
  HandleUnknownAction(actionName);
 }
}
Matt Hinze
A: 

Why not create a PreserveTempDataAttribute that you can decorate your Script action with. It can re-assign the TempData if it is not null.

JontyMC