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