【问题标题】:Pretty Paged Routing in MVCMVC 中的漂亮分页路由
【发布时间】:2013-01-18 01:27:10
【问题描述】:

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

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

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

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

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"))附加当前页面的页码。

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

【问题讨论】:

  • 如果在HomePagingroute 中将new { controller = "Home", action = "Index" } 更改为new { controller = "Home", action = "Index", page = UrlParameter.Optional } 怎么办?
  • 也许 actionLink 像这样 @Html.ActionLink("my site", "index", "Home", new { page = page });
  • 感谢您的建议。我终于让它工作了,但我仍然没有真正了解规则。

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


【解决方案1】:

我最终让它像这样工作。但老实说,这是通过反复试验。如果有人能解释为什么它会起作用,我相信这会对访问者非常有帮助。

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" }); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2016-02-07
    • 2014-01-25
    • 1970-01-01
    • 2019-06-20
    • 2015-02-25
    • 1970-01-01
    相关资源
    最近更新 更多