TempData in ASP.NET Core MVC


On the Visual Studio, create new ASP.NET Core MVC Web Application project

Select Empty Template

Click Ok button to Finish




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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddSessionStateTempDataProvider();
            services.AddSession();
        }

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

            app.UseSession();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.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;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Helpers;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace LearnASPNETCoreMVCWithRealApps.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<Product>(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 razor views as below:

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

@{
    Layout = null;
}
@model LearnASPNETCoreMVCWithRealApps.Models.Product

<!DOCTYPE html>

<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:

@{
    Layout = null;
}

@using LearnASPNETCoreMVCWithRealApps.Models;
@using LearnASPNETCoreMVCWithRealApps.Helpers;

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

<!DOCTYPE html>

<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

I recommend you refer to the books below to learn more about the knowledge in this article: