【问题标题】:Setting relative path for href设置href的相对路径
【发布时间】:2021-06-17 17:24:17
【问题描述】:

我正在研究 RAZOR。

_layout.cshtml 包含以下内容作为侧边栏

<a class="sidebar-brand" href="../Purchase/Index">

它打开 https://localhost/Purchase/Index

它适用于任何 CSHTML 页面。但是,如果我点击编辑页面,我可以看到上面的 URL

https://localhost/Purchase/Edit/46

从这个页面,如果我点击购买链接,那么它会尝试打开

https://localhost/Purchase/Purchase/Index

而不是

https://localhost/Purchase/Index

显然,../Procurment/Index 在这种情况下不起作用。

如何在 href 中处理这个问题?

【问题讨论】:

  • 当您使用“../Purchase/Index”等相关路径时,它将附加到routes.MapRoute() 调用生成的路由中。因此,您将获得 https://localhost/Purchase/Purchase/Index URL。
  • 如果需要参考Purchase控制器的Index动作方法使用href="/Purchase/Index"。这与href="~/Purchase/Index" 相同。
  • 非常感谢 Jacdaw。我没有意识到这一点。 ~ 作品

标签: html asp.net asp.net-mvc razor


【解决方案1】:

使用href="/Purchase/Index" 或href="~/Purchase/Index。 顺便说一句,从 MVC 4 开始,Razor 会自动检测以 ~/ 开头的属性,并自动插入 @Href 或 @Url 调用 你。

有关更多信息,请参阅以下文章: Tilde notation maps to the original URLs by using IIS URL rewrite in ASP.NET Web Pages Razor V3

还有一个帖子:ASP.NET MVC using Tilde in href attribute for relative paths

【讨论】:

    【解决方案2】:

    在剃刀视图中使用@Url.Action("ActionName","ControllerName") 始终是一个好习惯。 对于您的情况,应该是

    @Url.Action("Index","Purchase")
    

    【讨论】:

      猜你喜欢
      • 2013-08-24
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      相关资源
      最近更新 更多