重定向到操作,以便索引转到 example.com/controller/id



我们使用了一个具有"索引"操作的控制器:

[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使用这个公约而不打问号的方法吗?

更新了 5 年 2 月 17 日,以更正以下每条评论的控制器名称

您需要告知需要使用哪个路由模板来生成重定向的 URL。目前,您还没有一个 URL 模板可以生成像/my/index/1这样的 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 });

相关内容

最新更新