How to use RedirectToRoute(“routeName”) in MVC?

你。 提交于 2019-12-10 18:47:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!