【问题标题】:RedirectToAction for index to go to example.com/controller/id索引的 RedirectToAction 转到 example.com/controller/id
【发布时间】:2017-09-29 03:54:22
【问题描述】:

我们正在使用具有“索引”操作的控制器:

[Route("")]
[Route("Index/{id:int?}")]
[Route("{id:int?}")]    
public ActionResult Index(int? id)
    {
         var viewModel = new GroupViewModel();
....
        return View("Index", viewModel);

    }

我们可以通过使用example.com/my/example.com/my/indexexample.com/my/index/1 来执行此操作。这可以按我们的意愿工作。现在我们想使用example.com/my/index/1 语法重定向到这里。

当我们执行这一行时:

return RedirectToAction("Index", "My", new { id = 3 });

它将使用此 url 重定向:

example.com/my?id=3

我们希望它改用example.com/my/index/1

有没有人知道强制RedirectToAction 使用这个不带问号的约定的方法?

2017 年 5 月 2 日更新,以更正以下每个 cmets 的控制器名称

【问题讨论】:

  • Controller 是你的控制器的真实名称吗?
  • 没有。抱歉,我在上面的示例中将名称更新为 MyController。
  • 假设 MyController 是你的真实控制器名称,它应该是return RedirectToAction("Index", "My", new { id = 3 });
  • 我已根据您的 cmets 更新了控制器的名称。对困惑感到抱歉。感谢 CodeNotFound 和 Brian

标签: c# asp.net-mvc asp.net-mvc-routing redirecttoaction


【解决方案1】:

您需要告诉您需要使用哪个路由模板来生成重定向的 URL。目前您还没有一个可以生成像 /my/index/1 这样的 URL 的 URL 模板,即 "My/Index/{id:int?}"

首先,将该路由模板添加到您的操作并设置该路由的Name 属性,如下所示:

[Route("")]
[Route("Index/{id:int?}")]
[Route("My/Index/{id:int?}", Name = "MyCompleteRouteName")]
[Route("{id:int?}")]    
public ActionResult Index(int? id)
{
     var viewModel = new GroupViewModel();
....
     return View("Index", viewModel);
}

其次,您必须RedirectToRoute 而不是RedirectToActionRedirectToRoute 让您通过命名来选择您想要的模板。

所以你必须调用这条线:

RedirectToRoute("MyCompleteRouteName",  new { id = 3 });

代替

RedirectToAction("Index", "My", new { id = 3 });

【讨论】:

  • 这就是我们正在寻找的。谢谢@CodeNoteFound。
猜你喜欢
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-23
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多