首页 > 解决方案 > 将参数传递给 Controller 中的 Index()

问题描述

我正在使用 EF 构建一个 ASP>NET MVC Core 应用程序。Inventories我的控制器 Index() 和 OrderItem()有两种方法。当调用 OrderItem() 方法时,它会执行一些操作,一旦操作完成,我会尝试导航回索引页面。Index() 需要输入 ID 作为输入参数,否则返回 NOTFOUND()。

Index() 如下所示

   public async Task<IActionResult> Index(int? id, string sortOrder, string searchString,
                                           int? pageNumber, string currentFilter)
    {
        if (id == null)
        {
            return NotFound();
        }
       ......................
   } 

在我试图返回索引的同一控制器中的另一种方法如下所示

         return RedirectToAction("Index", "Inventories", new { customerID });
    

当 ye 操作完成并且代码尝试返回索引页面时,URL 就像https://localhost:44330/Inventories?customerID=460 我得到 Not Found 错误

在此处输入图像描述

如何使重定向有效,使 URL 看起来像https://localhost:44330/Inventories/Index/460

标签: asp.net-core-mvc

解决方案


尝试改变这个: return RedirectToAction("Index", "Inventories", new { customerID });

为此(如果您在同一控制器内重定向操作):

return RedirectToAction("Index", new { customerID = customerID });

或:返回 RedirectToAction("Index", new { "customerID" = customerID });

左键必须与您的路由参数名称相同,但不能干扰您的变量名称


推荐阅读