I have a controller "ServicesController" with the action "Edit" taking one string parameter "serviceId".
This controller has a route applied as shown and works as expected.
[Route("Services/Edit/{id}")]
public async Task<IActionResult> EditService(string id)
{
Service s = await _servicesService.GetService(id);
return View("EditService", s);
}
When I try to redirect to this route from another action I can only get the value to show as a query
return RedirectToAction("Edit", new { id = s.Id });
// redirects to /Services/Edit?id=exampleid
I've searched a few related answers where people have asked the same question but the solutions suggested don't work for me, presuming it's because I have the route decoration on my action maybe?
Ive also tried the below but that redirects to the calling action with the id
[Route("Services/Foo/{serviceId}")]
public async Task<IActionResult> Foo(string serviceId)
{
// redirects to /Services/Foo/exampleid
return RedirectToRoute("Edit", serviceId);
}
Where am I going wrong with this?
First argument of RedirectToAction
is actionName
, it is the name of the method, in our case it should be EditService
. Here is a link to the docs. So, I believe the correct version should be like this:
return RedirectToAction("EditService", new { id = s.Id });
It also has an overloaded version RedirectToAction(string actionName, string controllerName, object routeValues)
, it allows to specify controller in case you are redirecting not inside the same controller.
Regarding RedirectToRoute
, it accepts a name of the route, for that we need to set the name for our EditService(string id)
action like this:
[Route("Services/Edit/{id}", Name = "MyEditServiceRoute")]
public async Task<IActionResult> EditService(string id)
{
...
}
...
{
...
return RedirectToRoute("MyEditServiceRoute", serviceId);
}