繁体   English   中英

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

[英]how to use @Html.ActionLink to show Index View with parameters?

当我将@ActionLink与 Index 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" }
        );
    }

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

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

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

演示

你上面的代码没有错,请在“?”之前删除“/” 从您的 URL 并尝试使用以下链接示例:“ http://localhost:23594/NewsImages?selectedNewsid=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 url的模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM