0

Running this Index controller gives me errors, when I try to pass IEnumerable into Tempdata.

When debugging, TempData["ProductCategory"] seems to store expected data in Watch, but cannot render Html View after storing. However, the Html does show when I store a simple stirng.

    public IActionResult Index()
    {
        // This gives me http error 500
        //TempData["ProductCategory"] = productcategoryrepository.GetAllProductCategory();

        // This works at least!
        TempData["ProductCategory"] = "test"; 
        //TempData.Keep();
        return View();
    }

    public IEnumerable<ProductCategory> GetAllProductCategory()
    {
        return _context.ProductCategory.ToList();
    }

Other Info:

public partial class ProductCategory
{

    public ProductCategory()
    {
        Product = new HashSet<Product>();
    }
    public int ProductCategoryId { get; set; }
    public string ProductCategoryName { get; set; }
    public string ProductCategoryDescription { get; set; }

    public virtual ICollection<Product> Product { get; set; }
}

public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ImageLocation { get; set; }

    public int? ProductCategoryId { get; set; }
    public virtual ProductCategory ProductCategory { get; set; }
}
  • 2
    Refer [Complex Objects and TempData using .NET Core 2](https://dotnetevolved.com/2017/08/complex-objects-and-tempdata-using-net-core-2/) - you need to serialize your data –  Sep 29 '18 at 07:53
  • Two things come to my mind 1. Make sure there is no exception being thrown from your repository class (maybe some kind of SQLException) and 2. your page will not render correctly if you have not accessed the tempdata correctly (Try to bind your html page to an IEnumerable ) – Rakshith Murukannappa Sep 29 '18 at 12:29

1 Answers1

2

To be able to store data in sessions or temp data, the type must be serializable. IEnumerable<T> cannot be serialized. Try a List<T> instead.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1

Adam Vincent
  • 3,281
  • 14
  • 38