RedirectToRoute

 

RedirectToRoute其功能為使用指定的路由重新導向至指定的路由。

 

一、列出多載方法

名稱 說明
RedirectToRoute(Object routeValues) 使用指定的路由值重新導向至指定的路由。
RedirectToRoute(String routeName) 使用指定的路由名稱重新導向至指定的路由。
RedirectToRoute(RouteValueDictionary routeValues) 使用路由字典重新導向至指定的路由。
RedirectToRoute(String routeName, Object routeValues) 使用路由名稱和路由值重新導向至指定的路由。
RedirectToRoute(String routeName, RouteValueDictionary routeValues) 使用路由名稱和路由字典重新導向至指定的路由。

 

二、多載方法範例為

1、RedirectToRoute(Object)

public ActionResult About()
{
    return RedirectToRoute(new { action = "Index", controller = "Home" });
}

 

2、RedirectToRoute(String)

假設你有一個名為MessageHome的route

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "MessageHome",
            url: "m",
            defaults: new { controller = "Home", action = "Message", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        ); 
    }
}

後端controller為

public ActionResult About()
{
    return RedirectToRoute("MessageName");
}

則預設會被導到HomeController的Message頁面

 

3、RedirectToRoute(RouteValueDictionary)

public ActionResult About()
{
    System.Web.Routing.RouteValueDictionary RouteValueDictionary = new System.Web.Routing.RouteValueDictionary();
    RouteValueDictionary.Add("action", "Index");
    RouteValueDictionary.Add("controller", "Home");
    return RedirectToRoute(RouteValueDictionary);
}

 

4、RedirectToRoute(String, Object)

為了展示方便,MessageHome的route再做一下變化

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "MessageHome",
            url: "m/{controller}/{action}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

後端controller為

public ActionResult About()
{
    return RedirectToRoute("MessageHome", new { controller = "Home", action = "Message" });
}

 

5、RedirectToRoute(String, RouteValueDictionary)

public ActionResult About()
{
    System.Web.Routing.RouteValueDictionary RouteValueDictionary = new System.Web.Routing.RouteValueDictionary();
    RouteValueDictionary.Add("action", "Message");
    RouteValueDictionary.Add("controller", "Home");
    return RedirectToRoute("MessageHome",RouteValueDictionary);
}