Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC : Preserve TempData across multiple requests

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!

like image 751
user113003 Avatar asked Mar 10 '26 15:03

user113003


2 Answers

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

like image 143
Tormod Hystad Avatar answered Mar 12 '26 14:03

Tormod Hystad


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

like image 40
Alexander Prokofyev Avatar answered Mar 12 '26 14:03

Alexander Prokofyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!