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



当我将@ActionLink与索引操作名称一起使用时,此操作名称不会出现在浏览器链接中。

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

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

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 的名称,类似于路由中维护的默认名称。MapRoute然后它在URL中不可见,有时会产生问题。如果要使用索引作为操作名称,则只需在索引之前添加/

@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 的模式。

最新更新