Use TempData in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddSessionStateTempDataProvider();

            services.AddSession();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });

        }
    }
}

Create new folder named Models. In Models folder, create new entities class as below:

Create new class named Product.cs as below:

namespace LearnASPNETCoreMVC5.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}




Create new folder named Helpers. In this folder, create new helper named TempDataHelper.cs as below:

using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;

namespace LearnASPNETCoreMVC5.Helpers
{
    public static class TempDataHelper
    {
        public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
        {
            tempData[key] = JsonConvert.SerializeObject(value);
        }

        public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
        {
            object o;
            tempData.TryGetValue(key, out o);
            return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
        }
    }
}

Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

using LearnASPNETCoreMVC5.Helpers;
using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("demo")]
    public class DemoController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View("Index", new Product());
        }

        [Route("save")]
        [HttpPost]
        public IActionResult Save(int age, string username, Product product)
        {
            TempData["age"] = age;
            TempData["username"] = username;
            TempDataHelper.Put(TempData, "product", product);
            return RedirectToAction("showFlashAttributes", "demo");
        }

        [Route("showFlashAttributes")]
        public IActionResult showFlashAttributes()
        {
            return View("Result");
        }
    }
}




Create new folder named Views. In this folder, create new folder named Demo and add new views as below:

In Demo folder, create new view named Index.cshtml as below:

@model LearnASPNETCoreMVC5.Models.Product

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <form method="post" asp-controller="demo" asp-action="save">
        <fieldset>
            <legend>Single Values</legend>
            <table>
                <tr>
                    <td>Age</td>
                    <td><input type="text" name="age" /></td>
                </tr>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="username" /></td>
                </tr>
            </table>
        </fieldset>

        <fieldset>
            <legend>Product Information</legend>
            <table>
                <tr>
                    <td>Id</td>
                    <td>
                        <input asp-for="Id" />
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td>
                        <input asp-for="Name" />
                    </td>
                </tr>
                <tr>
                    <td>Price</td>
                    <td>
                        <input asp-for="Price" />
                    </td>
                </tr>

            </table>
        </fieldset>
        <input type="submit" value="Save" />
    </form>

</body>
</html>

In Demo folder, create new view named Success.cshtml as below:

@using LearnASPNETCoreMVC5.Models;
@using LearnASPNETCoreMVC5.Helpers;

@{
    var product = TempDataHelper.Get<Product>(TempData, "product") as Product;
}

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Success</title>
</head>
<body>

    <h3>Single Values</h3>
    <table border="1">
        <tr>
            <td>Age</td>
            <td>@TempData["age"]</td>
        </tr>
        <tr>
            <td>Username</td>
            <td>@TempData["username"]</td>
        </tr>
    </table>

    <h3>Product Info</h3>
    <table border="1">
        <tr>
            <td>Id</td>
            <td>@product.Id</td>
        </tr>
        <tr>
            <td>Name</td>
            <td>@product.Name</td>
        </tr>
        <tr>
            <td>Price</td>
            <td>@product.Price</td>
        </tr>
    </table>

</body>
</html>




Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Access Index action in Demo controller with following url: http://localhost:48982

Output

Click Save button submit form to Save action in Demo controller with following url: http://localhost:48982/demo/save

Output