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();
}
2
  • 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. Commented Jul 24, 2018 at 8:52
  • Follow the instructions on this link Commented Jan 22, 2019 at 10:45

4 Answers 4

9

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?}");
        });
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

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)

Comments

0

please place

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.