c# - MVC Net Core TempData 可以存储 Enumerables 吗?
问题描述
当我尝试将 IEnumerable 传递给 Tempdata 时,运行此索引控制器会给我错误。
调试时,TempData["ProductCategory"] 似乎在Watch中存储了预期的数据,但存储后无法渲染Html View。但是,当我存储一个简单的搅拌时,Html 会显示。
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();
}
其他信息:
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; }
}
解决方案
为了能够在会话或临时数据中存储数据,该类型必须是可序列化的。IEnumerable<T>
不能序列化。换一个试试List<T>
。
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1