Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TempData not carrying over during RedirectToAction

I have an interesting problem with the TempData object not passing values to another controller.

I set TempData["Enroll"] in the Enroll Controller's HttpPost method to an Enroll Model. I then read the TempData["Enroll"] object in the Register Controller's HttpGet method, but is empty/null.

I need to persist all of this data across 3 controllers.

Any thoughts?

Here is a code Snippet

//EnrollController.cs
[HttpPost]
public ActionResult Index(EnrollModel model)
{
   // ...
   TempData["EnrollModel"] = model;
   return RedirectToAction("Index", "Register");
}

// RegisterController.cs
public ActionResult Index(string type)
{
    RegisterModel model = new RegisterModel();

    EnrollModel enrollModel = TempData["EnrollModel"] as EnrollModel;
    model.ClientType = enrollModel.ClientType;
    // ...
}
like image 263
Mark Avatar asked Sep 04 '12 03:09

Mark


2 Answers

I've had an issue where TempData got lost during the redirect on my local machine.

I've checked web.config sessionState Setting which was InProc and therefore no problem.

It turned out that I got another setting in web.config, which was taken from production system. It looked like this:

<httpCookies requireSSL="true" />

After turning the requireSSL to false TempData workes fine.

like image 39
gabriel211 Avatar answered Sep 28 '22 03:09

gabriel211


I had the same problem today.

In this link some guys explain that RedirectAction method returns a HTTP 302 status to the browser, which causes the browser to make a new request and clear the temp, but I tried returning HTTP methods 303 (which is what the RedirectAction should be returning) and 307 also, and it didn't solve anything.

The only way of fixing the issue of TempData in my case was changing the sessionState directive of web.config to use StateServer instead of the default InProc. i.e:

<system.web>
    <sessionState mode="StateServer" cookieless="AutoDetect" timeout="30" stateConnectionString="tcpip=localhost:42424"></sessionState>
    ...
</system.web>

I figured this out when reading this Greg Shackles' article, where he explains how TempData works and build a custom TempDataProvider, which rely on MongoDB database instead of session like the default one.

Hope that my 4 hours researching helps someone to not waste their time.

like image 99
Dinei Avatar answered Sep 28 '22 03:09

Dinei