问题
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
回答1:
Try this:
return RedirectToRoute(new
{
controller = "Admin",
action = "Index",
id = null
});
You could also use RedirectToAction() method. It seems more intuitive.
回答2:
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.
来源:https://stackoverflow.com/questions/40910018/how-to-use-redirecttorouteroutename-in-mvc