Html.ActionLink包括额外的参数

时间:2011-12-05 19:15:13

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

使用以下代码:

@Html.ActionLink("News", "Index", new { controller = "News", area = "" }, new { @class = "News" })

我收到错误,因此当我在某篇特定新闻文章中时,链接生成为:

http://mywebsite/News/2011/12/2/my_slug

其中参数与我当前所在的页面匹配。这也发生在匹配相同url架构的其他控制器上(想象一下,我有另一个名为Presentations的控制器,完全匹配新闻的url方案)。从演示文稿页面,新闻链接将包括演示参数,这些参数不是新闻控制器的有效输入。有意义吗?

我的路线定义为:

        routes.MapRoute(
            "News-Archive", // Route name
            "News/Archive", // URL with parameters
            new { controller = "News", action = "Archive" }, // Parameter defaults
            new[] { "mywebsite.Controllers" }
        );

        routes.MapRoute(
            "News-Stub", // Route name
            "News/{year}/{month}/{date}/{slug}", // URL with parameters
            new { controller = "News", action = "Index" }, // Parameter defaults
            new[] { "mywebsite.Controllers" }
        );

        routes.MapRoute(
            "News-ByDay", // Route name
            "News/{year}/{month}/{day}", // URL with parameters
            new { controller = "News", action = "Archive" }, // Parameter defaults
            new[] { "mywebsite.Controllers" }
        );

        routes.MapRoute(
          "News-ByMonth", // Route name
          "News/{year}/{month}", // URL with parameters
          new { controller = "News", action = "Archive" }, // Parameter defaults
          new[] { "mywebsite.Controllers" }
        );

        routes.MapRoute(
          "News-ByYear", // Route name
          "News/{year}", // URL with parameters
          new { controller = "News", action = "Archive" }, // Parameter defaults
          new[] { "mywebsite.Controllers" }
        );

        routes.MapRoute(
          "News-Default", // Route name
          "News", // URL with parameters
          new { controller = "News", action = "Index" }, // Parameter defaults
          new[] { "mywebsite.Controllers" }
        );

有人可以解释问题在于我使用的是Html.ActionLink还是我的路线定义?

编辑:

将Actionlink更改为:

@Html.ActionLink("News", "Index", new { controller = "News", area = "", year = string.Empty, month = string.Empty, day = string.Empty, slug = string.Empty}, null)

从演示文稿页面调用时会产生此结果(这些值用于演示文稿,而不是有效的新闻项目):

http://mywebsite/News?year=2011&month=12&slug=seo_overview

不确定为什么导致重写改变。

1 个答案:

答案 0 :(得分:0)

动作链接假设当前的slug,因为没有提供slug:

使用

 ActionLink("News", "Index", new { controller = "News", area = "", slug="newslug"}, new { @class = "News" })

 ActionLink("News", "Index", new { controller = "News", area = "", slug = null}, new { @class = "News" })

设置slug = null也有可能重新使用当前的slug,在这种情况下设置slug = Empty String。