如何在视图中显示反序列化的 TempData 对象?
How to show deserialized TempData object in view?
反序列化我的 TempData 对象后,我在 Index2.cshtml 文件中收到 System.NullReferenceException: 'Object reference not set to an instance of an object.' 错误。如何在不出现此错误的情况下显示我的对象? (第一次在这里提问,如有错误请见谅。)
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>
更改您的代码:
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
收件人:
TempData["products"] = JsonSerializer.Deserialize<List<Products>>(data);
或者你可以return View(products)
使用数据:
public IActionResult Index2()
{
var data = TempData["products"].ToString();
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
return View(products);
}
查看:
@model List<Products>
<ul>
@foreach (var item in Model)
{
<li>@item.ProductName</li>
}
</ul>
反序列化我的 TempData 对象后,我在 Index2.cshtml 文件中收到 System.NullReferenceException: 'Object reference not set to an instance of an object.' 错误。如何在不出现此错误的情况下显示我的对象? (第一次在这里提问,如有错误请见谅。)
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>
更改您的代码:
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
收件人:
TempData["products"] = JsonSerializer.Deserialize<List<Products>>(data);
或者你可以return View(products)
使用数据:
public IActionResult Index2()
{
var data = TempData["products"].ToString();
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
return View(products);
}
查看:
@model List<Products>
<ul>
@foreach (var item in Model)
{
<li>@item.ProductName</li>
}
</ul>