带有可选部分的 MVC 路由

发布于 2024-10-18 20:57:14 字数 446 浏览 4 评论 0原文

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

/Articles/
/文章/页/2
/Articles/Page/3

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

我开始于:

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

问题在于,当我这样做时:

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

我的路线最终是: /Articles/Page/

I would like to create a route for my MVC page that looks like this:

/Articles/
/Articles/Page/2
/Articles/Page/3

I want the default page to be 1, but if the page is 1, then don't actually show the /Page/ piece.

I started out with:

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

The problem with this is that when I do:

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

My route ends up being: /Articles/Page/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

假扮的天使 2024-10-25 20:57:14

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

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)
{
    ...
}

You might need two route definitions for this (untested):

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

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

and your controller action:

public ActionResult Index(int page)
{
    ...
}
南街女流氓 2024-10-25 20:57:14

将两者都放入:

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

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

Put both in:

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

You don't need to do anything with the controller.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文