【问题标题】:ActionLinks reverting to querystring params when matching a route that does not contain that param匹配不包含该参数的路由时,ActionLinks 恢复为查询字符串参数
【发布时间】:2013-03-21 20:25:37
【问题描述】:

我正在努力实现 this 的目标,即将我的应用程序路由更改为如下所示:

hxxp://host/MyController/Widgets/3/AddWhatsit

此路线的视图将帮助用户将 Whatsit 添加到小部件 3。

同样,我希望创建新 Widget 的路线是:

hxxp://host/MyController/Widgets/Create

我已经创建了单独的路线来尝试和促进这一点。它们是:

           routes.MapRoute("DefaultAction",
                            "{controller}/{action}",
                            new {controller = "Home", action = "Index"});

           routes.MapRoute("Default",
                            "{controller}/{id}/{action}",
                            new {controller = "Home", action = "Index", id = UrlParameter.Optional});

我遇到的问题是,当我浏览到小部件的索引页面(/MyController/Widgets,匹配“DefaultAction”路由)时,任何会引入不属于该路由的新 url 参数的 ActionLinks 都会被打开成一个查询字符串值。因此,例如,Widget 3 的编辑链接将呈现为: Widget/Edit?id=3 instead of (what I would prefer): 小部件/3/编辑

我想我知道我没有把我的(可选)id 参数放在路由的末尾,这把事情搞砸了。

我应该把它吸干,然后把 id 留在路线的尽头吗?

【问题讨论】:

    标签: asp.net-mvc razor asp.net-mvc-4 asp.net-mvc-routing


    【解决方案1】:

    这是有可能实现的。要获得类似于 /Home/1/Index 的锚链接,请将路由设置为:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            name: "Custom",
            url: "{controller}/{id}/{action}"
            );
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
    

    然后,在视图中:

    @Html.ActionLink("Here", "Index", "Home", new { id = 5 }, null)
    

    你会得到这样的链接:

    <a href="/Home/5/Index">Here</a>
    

    Quirk 是限制自定义路由。在这种情况下,我删除了默认值,它们没有意义。当然还有路线的顺序。

    【讨论】:

    • 这让我非常接近。一个副作用是,如果我使用“/Widget/4/Whatsits”之类的路线在视图上,并且想要一个返回“Widget/Index”的操作链接,我会得到类似“Widget/4/Index”的内容,其中 4没有必要。这样就会从“自定义”路由跳转到“默认”。
    • 看起来我的次要问题是独立的(环境路径值),所以我将关闭这个问题。感谢您的回答。
    【解决方案2】:

    我认为您需要更改路线的顺序。请记住,MVC 会查看路由列表并选择 First 匹配的路由。带有 ID 参数的第二条路由更具体,因此应该在路由表中排在第一位。

    即使您在 ActionLink 中指定了 ID 参数,您也指定了控制器和操作。因此,RoutingEngine 选择了第一条路由。

    最后,移除 ID 属性的可选参数。由于您希望在拥有 Id 时选择该路由,因此您不希望它成为可选参数,而是希望它与该路由匹配。

    routes.MapRoute("Default","{controller}/{id}/{action}", 
       new {controller = "Home", action = "Index"});
    
    routes.MapRoute("DefaultAction", "{controller}/{action}", 
      new {controller = "Home", action = "Index"});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2015-11-07
      • 2013-11-26
      • 2016-07-03
      相关资源
      最近更新 更多