0

是否可以将路由参数的默认值设为路由中的另一个值?

例如:

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

parentid是强制性的,并且总是有价值的。如果没有为我指定值,currentid我希望它取parentid.

4

1 回答 1

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
于 2012-10-11T10:03:18.553 回答