2

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!

1
  • 1
    Please, show code sample where you set TempData and call RedirectToAction(). Commented May 27, 2009 at 9:21

5 Answers 5

8

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

I'd definitely recommend that article too!
4

Session is preserved between multiple requests.

1 Comment

Agreed - you're missing the point of TempData if you want it to do that
2

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);
    }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.