简体   繁体   English

如何让 routelink 返回正确的 URL?

[英]How to make routelink return the correct URL?

here is the procedure to duplicate the issue.这是复制问题的程序。

  1. start new mvc 4 project.启动新的 mvc 4 项目。
  2. add the following lines to the RegisterRoutes() method just before the "Default" route将以下行添加到 RegisterRoutes() 方法中的“默认”路由之前

    routes.MapRoute( name: "Test", url: "Test/{action}", defaults: new { controller = "Test", action = "Index" } );
  3. add the following to Index.cshtml and About.cshtml将以下内容添加到 Index.cshtml 和 About.cshtml

     @Html.RouteLink("link to TestController", "Test")

As you can see that the generated html code is different for the 2 pages.如您所见,生成的 html 代码对于 2 个页面是不同的。 I would expect the URL is "/Test" which is rendered correctly for Index.cshtml, but it become "/Test/About" for About.cshtml.我希望 URL 是“/Test”,它为 Index.cshtml 正确呈现,但它成为 About.cshtml 的“/Test/About”。

My question is if there is any documented way to generate the same correct URL.我的问题是是否有任何记录的方法来生成相同的正确 URL。 The above example is created just for demonstration purpose.上面的例子只是为了演示目的而创建的。 I would like to use the routing table information to generate menu.我想使用路由表信息来生成菜单。

It seems the engine is setting the action route value from the current page ("Index", "About").似乎引擎正在从当前页面(“索引”、“关于”)设置action路由值。 So one way to fix this is to "unset" that route value:因此,解决此问题的一种方法是“取消设置”该路由值:

@Html.RouteLink("link to Test Controller", "Test", new { action = String.Empty })

Register your route注册您的路线

 routes.MapRoute(
                name: "TestUrl",
                url: "Test",
                defaults: new { controller = "TestController", action = "TestAction" }
            );

add the following to TestAction.cshtml将以下内容添加到 TestAction.cshtml

 @Html.RouteLink("Test", "TestUrl")

Now your URL is /Test, hoping this will help you.现在您的 URL 是 /Test,希望这对您有所帮助。

Quickest way would be to just specify a blank action.最快的方法是指定一个空白操作。

@Html.RouteLink("link to TestController", "", "Test")

This will produce /Test这将产生/Test

For those who arrive here looking for .netcore razor page RouteLink syntax, don't use RouteLink's " page " reserved member.对于那些来到这里寻找.netcore razor page RouteLink语法的人,不要使用 RouteLink 的“页面”保留成员。 It will not work for the routeValues object as some have suggested.正如某些人所建议的那样,它不适用于 routeValues 对象。 Instead, use the following format:相反,请使用以下格式:

<a asp-page="RazorPage">RazorPage</a>

This handles trailing and the absence of trailing forward slashes.这处理尾随和尾随正斜杠的缺失。 The RazorPage is the name of the page without any characters after the first ".". RazorPage 是第一个“.”后没有任何字符的页面名称。

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

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