We are using a controller which has an "Index" action:
[Route("")]
[Route("Index/{id:int?}")]
[Route("{id:int?}")]
public ActionResult Index(int? id)
{
var viewModel = new GroupViewModel();
....
return View("Index", viewModel);
}
We can get to this action by using example.com/my/
or example.com/my/index
or example.com/my/index/1
. This works as we want. Now we want to redirect to this using the example.com/my/index/1
syntax.
When we execute this line:
return RedirectToAction("Index", "My", new { id = 3 });
It will redirect using this url:
example.com/my?id=3
We want it to use example.com/my/index/1
instead.
Does anybody know of a way to force RedirectToAction
to use this convention without the question mark?
Updated 5/2/17 to correct controller names per comments below
You need to tell which route template you need to use for generating the URL for the redirection. For the moment you haven't an URL template that can generate a URL like /my/index/1 which is "My/Index/{id:int?}"
First,add that route template to your action and set the Name
property of that route like this:
[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);
}
Second, you must RedirectToRoute
instead of RedirectToAction
. RedirectToRoute
let you choose which template you want by giving its name.
So you must call this line :
RedirectToRoute("MyCompleteRouteName", new { id = 3 });
Instead of
RedirectToAction("Index", "My", new { id = 3 });