ASP.NET Core - Using TempData

ASP.NET Core - Using TempData

TempData is next to ViewBag and ViewData a common way to handle data for Requests and Views.

ViewData and ViewBag is only available in the current request and current View. TempData has the functionality to store data from one request to another. Keys inside TempData will be removed if you read them once!

In older versions TempData was able to use by defaule. In ASP.NET Core it is also built-in by default, but not active. It wont work if you do not activate some stuff.

Sessions

First of all the TempData is based on Sessions. So you have to add a Session Middleware to the ASP.NET Core Pipeline. Otherwise it always will be null. You will not get any error!

services.AddSession();

You also need a TempData Provider.

services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();

Here it is a cookie provider which means all TempData stuff will be put into a cookie from request A and will be read again in request B.

Now you also have to use the Session registration:

app.UseSession();

Source

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.

    services.AddMvc();

    services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
    services.AddSession();

    // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseDeveloperExceptionPage();

    app.UseStaticFiles();

    app.UseSession();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now you can use the TempData to pass data from one action to another.

public class TempDataDemoController : Controller
{
    public IActionResult RequestA()
    {
        ViewData["MyKey"] = "Hello TempData!";

        return RedirectToAction("RequestB");
    }

    public IActionResult RequestB()
    {
        return Content(ViewData["MyKey"] as string);
    }
}