【发布时间】:2022-01-06 06:35:10
【问题描述】:
我得到 System.NullReferenceException: 'Object reference not set to an instance of an object.' 反序列化我的 TempData 对象后 Index2.cshtml 文件中的错误。如何在不出现此错误的情况下显示我的对象? (这是我第一次在这里问如果我犯了错误。)
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>
【问题讨论】:
-
嗨@ıremk,你使用
JsonSerializer.Serialize(products);,它似乎包含在 System.Text.Json 包中,它位于 asp.net 核心而不是 asp.net 中,对吧? -
如果你使用asp.net,
JsonSerializer使用的是哪个包?我认为您的意思是 .NET 5/.NET 6 目标框架是 .net core。 -
不好意思是asp.net core,我正在学习所以是新手。
-
嗨@@ıremk,我已经测试了你的代码并重现了你的问题。您造成的问题没有将反序列化模型设置为TempData。
标签: c# asp.net-core model-view-controller razor