2012-10-11 72 views
0

是否有可能使路由參數的默認值是來自路由的另一個值?路由參數的默認值是否可以是另一個路由參數的值?

例如例如:

routes.MapRoute(null, 
    "{controller}/{action}/{parentid}/{currentid}", 
    new { controller = "Home", action = "Display", currentid = "{parentid}" } 
); 

parentid是強制性的,並將始終有一個值。如果沒有指定currentid的值,我希望它的值爲parentid

回答

2

我不知道是否支持此功能開箱即用,但你總是可以寫一個自定義的路由來實現它:

public class MyRoute : Route 
{ 
    public MyRoute() : 
     base(
      "{controller}/{action}/{parentid}/{currentid}", 
      new RouteValueDictionary(new 
      { 
       controller = "home", 
       action = "display", 
       currentid = UrlParameter.Optional 
      }), 
      new RouteValueDictionary(new 
      { 
       // adjust the constraint if your ids are not numeric 
       // but you must have a constraint when a route parameter is 
       // non optional unless this is the last parameter 
       parentid = @"^([0-9])+$" 
      }), 
      new MvcRouteHandler() 
    ) 
    { 
    } 

    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var rd = base.GetRouteData(httpContext); 
     if (rd == null) 
     { 
      return null; 
     } 

     var currentid = rd.Values["currentid"] as string; 
     if (!string.IsNullOrEmpty(currentid)) 
     { 
      return rd; 
     } 

     rd.Values["currentid"] = rd.Values["parentid"]; 
     return rd; 
    } 
} 

,然後註冊此路線:

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

    routes.Add("myroute", new MyRoute()); 
} 

現在假設您已經定義了以下控制器:

public class HomeController : Controller 
{ 
    public ActionResult Display(int parentid, int currentid) 
    { 
     return Content(string.Format("{0}, {1}", parentid, currentid)); 
    } 
} 

您可以通過以下方式提出要求:

  • /home/display/123 - >的parentid = 123和currentid = 123
  • /home/display/123/456 - >的parentid = 123和currentid = 456