加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

razor – 使用ActionLink将null参数传递给控制器

发布时间:2020-12-16 07:19:02 所属栏目:asp.Net 来源:网络整理
导读:我有一个列出一堆类别的视图: ul li@Html.ActionLink("All","Index","Products")/li @foreach (var item in Model.ProductCategories) { li@Html.ActionLink(item.Name,new { id = item.Id },null)/li }/ul 如图所示,我应该得到一个类别链接列表,最上面的一
我有一个列出一堆类别的视图:

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

如图所示,我应该得到一个类别链接列表,最上面的一个是“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);
}

所以类别应该始终相同.但是当id为null时,项应显示每个项,当设置id时,项应显示特定类的项.

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

/产品/首页/ 3

大!现在我点击“全部”链接,但它将我路由到/ Products / Index / 3,即使我显然没有传递参数.我尝试传递一个空值:

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

但我得到错误:无法将’null’分配给匿名类型属性.

如何强制null传递给我的索引控制器?

解决方法

你的控制器动作会很高兴接受一个可以为空的int,所以给它一个可以为空的int就像这样!

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读