gpt4 book ai didi

razor - 使用 ActionLink 将空参数传递给 Controller

转载 作者:行者123 更新时间:2023-12-04 17:37:10 24 4
gpt4 key购买 nike

我有一个列出一堆类别的 View :

<ul>
<li>@Html.ActionLink("All", "Index", "Products")</li>
@foreach (var item in Model.ProductCategories)
{
<li>@Html.ActionLink(item.Name, "Index", new { id = item.Id }, null)</li>
}
</ul>

如图所示,我应该得到一个类别链接列表,最上面的一个是“All”,下面的是各自的类别名称,一个 id 传递给 Controller ​​。

我的 Controller 看起来像这样:
public ActionResult Index(int? id)
{
var categories = _productCategoryRepository.GetAll().OrderByDescending(f => f.Name);
var items = id == null
? _productItemRepository.GetAll().OrderBy(f => f.Name).ToList()
: _productCategoryRepository.GetSingle((int)id).ProductItems.OrderBy(f => f.Name).ToList();

var model = new ProductsViewModel()
{
ProductCategories = categories,
ProductItems = items
};

return View(model);
}

所以类别应该总是相同的。但是项目应该显示每个项目,当 id 为空且特定类别的项目id 设置。

这一切都非常好,所以当我点击一个类别链接时。我得到这样的网址:

/产品/索引/3

伟大的!现在我单击“全部”链接,但它会将我路由到 /产品/索引/3 即使我显然没有向它传递参数。我尝试传递一个空值:
@Html.ActionLink("Alle", "Index", "Products", new { id = null })

但是我随后收到错误:无法将“空”分配给匿名类型属性。

如何强制将 null 传递给我的索引 Controller ?

最佳答案

您的 Controller 操作将很高兴接受可为空的 int ,所以给它一个可以为空的 int像这样!

@Html.ActionLink("Alle", "Index", "Products", new { id = (int?)null })

关于razor - 使用 ActionLink 将空参数传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com