我正在尝试使用
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();
}
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>
}