Asp.net Core TempData lifetime and search term
Asked Answered
W

2

2

In my index I added a search field.

When user enter a search term and click filter the index (Index) is filtered. So far so good.

What I would like to achieve is that if the user performs other operations (edit, details, delete, etc) in the same controller and returns to the Index, I would like the search to be restored.

To do this, I used TempData but without success.

In the various forums / tutorials I found conflicting about lifetime. Some say:

lifetime of an object placed in TempData is exactly one additional request.

See this stackoverflow article

On another site i found:

Data stored in TempData will be alive in the cookie until you read it from the TempData dictionary.

See this article

So where is the truth: Only one sub request or when I read the TempData ?

My tests says the second: "until you read it" (or when expire)

Here my code on startup

public void ConfigureServices(IServiceCollection services)
{
    // [..]
    // Relevant code only
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromMinutes(15);
        options.CookieHttpOnly = true;
    });

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{

    // [..]
    // Relevant code only

    app.UseSession();

}

On my controller

public async Task<IActionResult> Index(int page, string search)
{
    search = search ?? TempData["Search"]?.ToString();
    // Query with search data

    TempData["search"] = search;
}

If I search on this controller the TempData save the search term.

If, after searching in the list, I navigate to other pages and then return here, the search term is still present

I already know that exist .Keep, .Peek and other methods for manage the TempData

Questions

  • How manage the search term between actions ?
  • How work the TempData (until re-read or on ONE addictional request) ?
Wendywendye answered 7/6, 2017 at 15:55 Comment(2)
TempData is built on top of session, so you have to register Session and keep in mind its cookie-based essence learn.microsoft.com/en-us/aspnet/core/fundamentals/app-stateEsquimau
Already know this infos.Wendywendye
M
3

Judging by many older Stack Overflow posts and articles out there, it seems TempData only lasted until the next request in prior versions of ASP.NET. However, that is not the case as of .NET Core according to Microsoft:

ASP.NET Core exposes the Razor Pages TempData or Controller TempData. This property stores data until it's read in another request. The Keep(String) and Peek(string) methods can be used to examine the data without deletion at the end of the request. Keep marks all items in the dictionary for retention.

Another claim I see repeatedly about TempData is how it is implemented using sessions, but that isn't the default mechanism as of .NET Core:

The cookie-based TempData provider is enabled by default. To enable the session-based TempData provider, use the AddSessionStateTempDataProvider extension method.

Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1#tempdata

Merissameristem answered 9/9, 2020 at 19:5 Comment(2)
Finally someone managed to provide insightfull comment on TempData. I came across many different exmplanations of TempData, sometimes conflicting.Cholla
Even in the old World, TempData lasted longer, than one requestCoalfield
A
0

"If, after searching in the list, I navigate to other pages and then return here, the search term is still present".

This is not the way it appears to work in Net Core 7 with Razor pages and no controllers (from my testing). TempData variables set in Request 1/Page 1 are available for the next request (Request 2/Page 2) but not for the subsequent request (whether this is Request 3/Page 1 or Request 3/Page 3). This applies whether the temp variables are read in Page 2 or not, or whether they are declared as [TempData] in Page 2 or not. To make them accessible in Request 3 they must be explicitly read and then rewritten in Page 2.

This behaviour seems to be the same whether the session or tempdata storage cookie is used.

You can see that this is a sensible failsafe if they are designed only as a way to pass data to the next request. Otherwise if never read they would hang about and cause unexpected behaviour when, for instance, a page that uses those variables is visited some time later in the session.

It does make it slightly clunky to return to a list page and display the same selection after say an update - a pretty normal requirement. I have tried session strings instead but a) you have to convert to and from strings and b) you must explicitly clear them if you are to avoid the unexpected behaviour risk above.

Edit. The only way I can get the TempData items to persist beyond the first Get of the first request so that they are there for a subsequent page is to bind them and hide them inside the form. They then get rewritten to the cookie on the Post.

Anesthesia answered 27/7, 2023 at 10:35 Comment(2)
This question is 6 YEAR old and refers to .NET Core 1.0Wendywendye
Well spotted Max. Still, it came up (and helped) when I needed help with TempData so I have taken the time to add some updates.Anesthesia

© 2022 - 2024 — McMap. All rights reserved.