带可选部分的MVC路由

时间:2011-02-22 21:27:00

标签: asp.net-mvc asp.net-mvc-routing

我想为我的MVC页面创建一个如下所示的路径:

/文章/
/条/页/ 2
/文章/页/ 3

我希望默认页面为1,但如果页面为1,则实际上不显示/ Page / piece。

我开始时:

routes.MapRoute(
    "Articles",
    "Articles/Page/{page}",
            new { controller = "Articles", action = "Index", page = 1 }
);

问题在于我做的时候:

 <%= Html.RouteLink("Articles", new { page = 1 }) %>

我的路线最终成为:/ Articles / Page /

2 个答案:

答案 0 :(得分:3)

您可能需要两个路线定义(未经测试):

routes.MapRoute(
    "ArticlesDefault",
    "Articles",
    new { controller = "Articles", action = "Index", page = 1 }
);

routes.MapRoute(
    "Articles",
    "Articles/Page/{page}",
    new { controller = "Articles", action = "Index" }
);

和您的控制器操作:

public ActionResult Index(int page)
{
    ...
}

答案 1 :(得分:1)

将两者放在:

// This will match routes where the page equals one. Since the page can't
// be specifed here, it will drop to the next one for page values other
// than 1.
routes.MapRoute("Articles",
                "Articles",
                new { controller = "Articles", action = "Index", page = 1 } 
); 

// This route handles pages other than 1
routes.MapRoute(null,
                "Articles/Page/{page}",
                new { controller = "Articles", action = "Index" }
); 

您无需对控制器执行任何操作。