【问题标题】:How to use MVC (.NET 4.5) url routes instead if url parameters如果 url 参数,如何使用 MVC (.NET 4.5) url 路由
【发布时间】:2014-04-02 23:34:36
【问题描述】:

使用 ASP MVC,我有以下 Action 链接,

<a href="@Url.Action("Page", "Content", new { publicationId = publication.PublicationId })">@publication.Title</a>

用于控制器操作

public ActionResult Page(int publicationId)

这可行,但 URL 看起来像这样

Content/Page?publicationId=129

我更喜欢它看起来像

内容/页面/129

有没有办法做出改变?

【问题讨论】:

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


    【解决方案1】:

    您需要为您的Content 控制器定义一个路由以使用您的publicationId 参数 在你的App_Start\RouteConfig.cs 上面添加Default 路由:

    routes.MapRoute(
        name: "ContentPage",
        url: "Content/{action}/{publicationId}",
        defaults: new { controller = "Content", action = "Page", publicationId = UrlParameter.Optional }
    );
    

    如果您希望它仅特定于 Page 操作:

    routes.MapRoute(
        name: "ContentPage",
        url: "Content/Page/{publicationId}",
        defaults: new { controller = "Content", action = "Page", publicationId = UrlParameter.Optional }
    );
    

    【讨论】:

    • publicationId 在这种情况下可能不是可选的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2012-07-17
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多