如何使用@ Html.ActionLink显示带有参数的索引视图?

时间:2019-06-22 05:59:40

标签: c# asp.net model-view-controller

当我将@ActionLink与索引ActionName一起使用时,该ActionName不会出现在浏览器链接中。

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

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

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

3 个答案:

答案 0 :(得分:1)

如果您在ActionLink中提供的动作或ID名称类似于在route.MapRoute中维护的默认名称,则它在URL中不可见,有时会造成问题。 如果要使用索引作为操作名称,则只需在索引之前添加/

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

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

DEMO

答案 1 :(得分:0)

上面的代码没什么错 请在“?”之前删除“ /”。从您的URL中尝试以下链接 示例:“ http://localhost:23594/NewsImages?selectedNewsid=1

答案 2 :(得分:-1)

创建新路线

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

然后正确的链接将是: http://localhost:23594/NewsImages/1

请调整代码,这是MVC网址的格式。