asp.net mvc路由的path_prefix

时间:2009-04-29 16:40:45

标签: asp.net-mvc routing

我阅读了this文章,了解如何在rails上的ruby中为路由添加前缀。我希望能够用asp.net mvc做同样的事情

所以我希望能够定义一条路线,如:

/photographers/1/photos/2   //photo 2 of photographer with id 1
/photographers/1/photos     //all of photographer with id 1

任何提示?

修改

“摄影师/ {id} / photos / {photoID}” - 似乎做得很好,但我怎么能支持

RedirectToAction<PhotosController>(x => x.Add());

我想重定向到:/ photographers / 1 / photos / add

2 个答案:

答案 0 :(得分:3)

像这样定义你的路线:

routes.MapRoute(
    "Photographers",
    "photographers/{id}/photos/{photoID}",
    new { controller = "Photographers", action = "Photo", photoID = null });

然后像这样定义你的控制器动作:

public ActionResult Photo(int id, int? photoID)
{
    // If photoID is not null, show just that photo.
    // Otherwise, show all photographs.
}

答案 1 :(得分:0)

您可以使用regex routing或使用wildcards in your routing table,以便{id *}与摄影师默认控制器的/1/photos/2匹配,解析字符串,然后重定向到相应的操作。< / p>

另请查看有关嵌套资源的this帖子。

RouteTable.Routes.Add(
        new Route { Url = "events/[eventId]/tickets/[action]/[id]", 
                    Defaults = new { controller = "Tickets", 
                                     action = "List", id = (string)null }, 
                    RouteHandler = typeof(MvcRouteHandler) });