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

17.1k Views Asked by At

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

2

There are 2 best solutions below

1
On

Try this:

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

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

1
On

This is because of the route you have defined. RedirectToRoute() redirects to the route you have defined. The url you have defined for "pattern2" is "{controller}/{action}/{id}". If you want to use the overload which only accepts the routeName, then you need explicitly define the url in your RouteConfig. Example:

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

If you do not want to define the url explicitly, then you need to use a different overload of RedirectToRoute() which accepts the routeValues object.