将参数传递给 Controller 中的 Index()

Pass parameters to the Index() in Controller

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

Index() 如下所示

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

在我尝试 return 到索引的同一控制器中的另一种方法如下所示

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

当您的操作完成并且代码尝试 return 索引页面时,URL 就像 https://localhost:44330/Inventories?customerID=460 我收到未找到错误

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

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

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

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

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

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