MVC中的漂亮分页路由

时间:2013-01-18 01:27:11

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

我已经看过Paging and routing in ASP.Net MVC,但我不能让它为我工作。

在我的主页上,我想为我的分页生成以下漂亮的网址:

http://mysite
http://mysite/2
http://mysite/3 

如果没有路由,寻呼机生成的默认网址将是:

http://mysite/?page=1
http://mysite/?page=2
http://mysite/?page=3 

到目前为止,我的RouteCollection是:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
    "HomePaging",
    "{page}",
    new { controller = "Home", action = "Index" },
    new { page = @"\d+" },
    new[] { "MySite.Controllers" });

routes.MapRoute(
    "HomePagingFirst",
    "{controller}",
    new { controller = "Home", action = "Index", page = 1 },
    new[] { "MySite.Controllers" });

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new[] { "MySite.Controllers" });

}

这会产生以下路线:

http://mysite/1
http://mysite/2
http://mysite/3 

这不仅会为第一页生成非规范路由,而且还会导致生成的所有链接(如下面的@Html.ActionLink("my site", "Index", "Home"))都附加当前页面的页码。

知道怎么做吗?如果可以,我们非常欢迎您提供简短的解释和答案。

1 个答案:

答案 0 :(得分:0)

我最终让它像这样工作。但诚实地说,这是通过反复试验。如果有人能够解释它为什么有效,我相信这对访客非常有帮助。

routes.MapRouteLowercase(
    "HomePaging",
    "{controller}",
    new { controller = "Home", action = "Index", page = UrlParameter.Optional },
    new { page = @"\d+" },
    new[] { "MySite.Controllers" });

routes.MapRouteLowercase(
    "HomeFirstPage", // Route name
    "{page}", // URL with parameters
    new { controller = "Home", action = "Index", page = 1 },
    new { page = @"\d+" },
    new[] { "MySite.Controllers" });