How to use RedirectToRoute("routeName") in MVC?

Lijin Durairaj picture Lijin Durairaj · Dec 1, 2016 · Viewed 14.5k times · Source

I am just puzzled on why is my RedirectToRoute() method not working. I have a RouteConfig.cs file like this

routes.MapRoute(
    "pattern1",
    "{action}",
    new { controller = "Home", action = "About" }
);

routes.MapRoute(
    "pattern2",
    "{controller}/{action}/{id}",
    new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
);

on this configuration my default controller Home and action About is getting called, now in the action method I am calling RedirectToRoute() with the following value like this

public ActionResult Index()
{
    return View();
}
public ActionResult About()
{
    return RedirectToRoute("pattern2");
}

Why is the RedirectToRoute() not calling Admin/Index action

Answer

rafrcruz picture rafrcruz · Dec 1, 2016

Try this:

return RedirectToRoute(new 
{ 
    controller = "Admin", 
    action = "Index", 
    id = null 
});

You could also use RedirectToAction() method. It seems more intuitive.