'How to show deserialized TempData object in view?

I'm getting System.NullReferenceException: 'Object reference not set to an instance of an object.' error in Index2.cshtml file after deserializing my TempData object. How can I show my object without getting this error? ( This is my first time asking in here sorry if I made mistakes.)

  var products = new List<Products>
            {
                new Products {Id=56, ProductName="x",Quantity=45},
                new Products {Id=55, ProductName="y",Quantity=5},
                new Products {Id=54, ProductName="z",Quantity=4},
                new Products {Id=53, ProductName="t",Quantity=8},
                new Products {Id=52, ProductName="k",Quantity=12}
            };
         
            string data = JsonSerializer.Serialize(products);
            TempData["products"] = data;
            return RedirectToAction("Index2");

 public IActionResult Index2()
        {
            var data = TempData["products"].ToString();
            List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
            
        return View();
        }

**Index2.cshtml**
<ul>
    @foreach(var item in TempData["products"] as List<Products>)
    {
                <li>@item.ProductName</li>
            }
</ul>


Solution 1:[1]

Change your code from:

List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);

To:

TempData["products"] = JsonSerializer.Deserialize<List<Products>>(data);

Or you can use return View(products) to use the data:

public IActionResult Index2()
{
    var data = TempData["products"].ToString();
    List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);

    return View(products);
}

View:

@model List<Products>
<ul>
    @foreach (var item in Model)
    {
        <li>@item.ProductName</li>
    }
</ul>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1