5

I would like to use TempData in my .net core mvc application. I followed the article from https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#tempdata

I always get NULL Here is my code:

public async Task<ActionResult> Index(RentalsFilter filter)
{
    TempData["test"] = "ABC";
    return View();
}

public ActionResult Create()
{
    var abc = TempData["test"].ToString();
    return View();
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
Si Thu
  • 1,185
  • 1
  • 13
  • 21
  • What is your operation step? If you access `Index` first, and then `Create`, will it be null? I fail to reproduce this issue, could you share us a project. Maybe, you could try `Session` to store the values. – Edward Jul 24 '18 at 08:52
  • Follow the instructions on this [link](https://stackoverflow.com/a/51740631/2572010) – franklores Jan 22 '19 at 10:45

4 Answers4

8

Had similar issue due to GDRP (https://learn.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.1). If you want have it up and running without worring about GDPR you can just disable it. The config below also uses cookies (default) instead of session state for TempData.

Startup.cs

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.Configure<CookieTempDataProviderOptions>(options =>
        {
            options.Cookie.IsEssential = true;
        });

...

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy(); // <- this

        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
Artur Kedzior
  • 3,994
  • 1
  • 36
  • 58
4

Did you configure TempData as said in the doc:

in ConfigureServices method add:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddSessionStateTempDataProvider();

services.AddSession();

And in Configure method you should add:

app.UseSession();
othman.Da
  • 621
  • 4
  • 16
2

The answer that worked for me (for asp.net Core 2.2) was

in Startup.Configure() app.UseCookiePolicy(); should be after app.UseMVC();

Which someone above has linked to in the comments from this stackoverflow answer

This is in addition to having

app.UseSession() (in Configure)

and

services.AddSession() (in ConfigureServices)

jazza1000
  • 4,099
  • 3
  • 44
  • 65
0

please place

@{TempData.Keep("test");}

in your HTML file. It will persist for the next request.

WinnerIT
  • 125
  • 8