Dan*_*sen 5 parameters controller actionlink razor asp.net-mvc-4
我有一个列出一堆类别的视图:
<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>
Run Code Online (Sandbox Code Playgroud)
如图所示,我应该得到一个类别链接列表,最上面的一个是"All",下面的是相应的类别名称,id传递给控制器.
我的控制器看起来像这样:
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);
}
Run Code Online (Sandbox Code Playgroud)
所以类别应该始终相同.但是,项目应显示出每一个项目,当ID是空当该特定类别的物品ID设置.
这一切都非常好,所以当我点击一个类别链接.我这样得到了网址:
/产品/首页/ 3
大!现在我点击"全部"链接,但它将我路由到/ Products/Index/3,即使我显然没有传递参数.我尝试传递一个空值:
@Html.ActionLink("Alle", "Index", "Products", new { id = null })
Run Code Online (Sandbox Code Playgroud)
但我得到错误:无法将'null'分配给匿名类型属性.
如何强制null传递给我的索引控制器?
你的控制器动作会很高兴接受一个可空的int,所以给它一个int像这样的可空!
@Html.ActionLink("Alle", "Index", "Products", new { id = (int?)null })
Run Code Online (Sandbox Code Playgroud)