Search code examples
c#asp.net-mvcrazorroutesactionlink

How to redirect to another action or route?


In my Razor code I have the following action link.

@Html.ActionLink("poof", "Poof", new { Id = Model.Id })

What I want to happen is that the Poof method is invoked but then, I want the computer to navigate to another view - e.g. Show.

public ActionResult Show(Guid id)
{
  return View(...);
}

public void Poof(Guid id)
{
  ...
  RedirectToRoute("Show", new {Id = id});
  RedirectToAction("Show", new {Id = id});
}

I've tried both RedirectToRoute and RedirectToAction but in both cases, I landed at an empty screen. A closer look at the URL showed that I'm getting stuck at the .../Poof/... route instead of being ushered to .../Show/... and I can't figure out how to bounce on to the appropriate link.

I'm following something like this answer but since the break-point in Show action isn't hit on (on redirect, that is), I start to wonder if it's more appropriate to play around with route mapping like this blog.


Solution

  • Even though Poof is redirecting to another action, it is still an action itself and as such it needs to return an ActionResult. RedirectToAction returns an ActionResult for just this reason.

    public ActionResult Poof(Guid id)
    {
        // ...
    
        return RedirectToAction("Show", new {Id = id});
    }