4

I'm using TempData to carry messages with Redirect after Post. The controller sets the tempdata as shown here:

TempData["message"]="foo";
return RedirectToAction("Index");

In the _Layout.cshtml, I have the following fragment:

@{var temp = TempData["message"] as string; }
@if ( temp != null)
{
     <div class="message">@temp</div>
}

My problem is now, that after the redirect, the message is not displayed. However, on the request that follows immediately the redirect (refresh or any other page), the message is displayed. After being displayed, it is removed from the session as expected.

How can I make my TempData display on the page I redirect to?

MZywitza
  • 3,121
  • 1
  • 17
  • 12
  • 1
    did you solve this? Im facing exactly the same issue. – luisgepeto Aug 02 '18 at 14:01
  • For those still stumbling upon this, setting up Session State as opposed to the default cookie method solved this for me. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1#session-state – perustaja Jan 22 '20 at 00:27

2 Answers2

1

You need to use

TempData.Keep(key);
Buba20
  • 21
  • 2
0

When you do:

TempData["message"] = "foo";
return RedirectToAction("Index");

The message will be displayed when the Index page to which you are redirecting renders its view.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    The problem is that it does not display in the redirected page, but in the request after it instead. Please reread the question. – MZywitza Nov 24 '11 at 06:04