首页 > 解决方案 > 如何使用@Html.ActionLink 显示带参数的索引视图?

问题描述

当我使用@ActionLinkIndex ActionName 时,此 ActionName 不会出现在浏览器链接中。

@Html.ActionLink(linkText: "return", actionName: "Index", controllerName: "NewsImages"
, routeValues: new { selectedNewsid = 1 }, htmlAttributes: null)

此操作在浏览器上显示以下链接: http://localhost:23594/NewsImages/?selectedNewsid=1 但是当我使用另一个 ActionName 时,链接正确显示!我究竟做错了什么?这是我的路由配置:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "GPTKish.Controllers" }
        );
    }

标签: c#asp.netmodel-view-controller

解决方案


如果您在 ActionLink 中提供的操作名称或 id 类似于在 routes.MapRoute 中维护的默认名称,那么它在 URL 中不可见,并且有时会产生问题。如果您想使用索引作为操作名称,那么只需在索引之前添加 /

@Html.ActionLink(linkText: "return", actionName: "/Index", controllerName: "NewsImages"
    , routeValues: new { SelectedNewsid = 1 }, htmlAttributes: null)

(PS:在演示中,我将控制器名称更改为 Home)

演示


推荐阅读