从 TempData[] 检索列表会导致其为空

问题描述 投票:0回答:1

我正在尝试使用

List<int>
从 ASP.NET Core 中的 2 个方法传递
TempData[]
。在 Category 方法中,检索信息时
productID
为 null,而
TempData["Products"]
不为 null 并且包含我之前添加的 2 个数字 - 1,2。

public IActionResult Homepage()
{
    List<int> productIDs = new List<int> { 1, 2};
    TempData["Products"] = productIDs;
    return View();
}

public IActionResult Category(string categoryName)
{
    List<int> productIDs = TempData["Products"] as List<int>;
    return View();
}
c# asp.net-core
1个回答
0
投票

您可以在文档中看到有关

TempData
生命周期的一些有用信息:

ASP.NET Core 公开 Razor 页面

TempData
或控制器
TempData
。 此属性会存储数据,直到在另一个请求中读取该数据为止。这
Keep(String)
Peek(string)
方法可用于检查数据 请求结束时不删除。保留所有项目的标记 记忆词典

因此,这里是如何在您的案例中使用它的示例。

在控制器中:

public IActionResult Homepage()
{
    List<int> productIDs = new List<int> { 1, 2 };
    TempData["Products"] = productIDs;
    return View();
}

[HttpPost]
public IActionResult Category(string categoryName)
{
    var data = new List<int>();
    var key = "Products";
    if (TempData.ContainsKey(key) && TempData[key] is IEnumerable<int> productsid)
    {
        data = productsid.ToList<int>();
    }
     
    //... using the `data`

    return View();
}

视角:

@{
    var key = "Products";
    var data = new List<int>();
    if (TempData.ContainsKey(key) && TempData[key] is IEnumerable<int> productsid)
    {
        data = productsid.ToList<int>();
    }
    TempData.Keep(key);
}
@using (Html.BeginForm("Category", "Home", new { categoryName = "some text" }))
{
    @* .... some code using the `data` *@
    <button type="submit" class="btn btn-primary">Save</button>
}
© www.soinside.com 2019 - 2024. All rights reserved.