是否可以将路由参数的默认值设置为路由中的另一个值?
e.g。类似的东西:
routes.MapRoute(null,
"{controller}/{action}/{parentid}/{currentid}",
new { controller = "Home", action = "Display", currentid = "{parentid}" }
);
parentid
是强制性的,并且总是有价值。如果没有为currentid
指定任何值,我希望它取parentid
的值。
答案 0 :(得分: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