如何在MVC应用程序中解析JavaScript的相对路径

How to resolve relative path from JavaScript within MVC application

本文关键字:JavaScript 相对 路径 MVC 应用程序      更新时间:2023-09-26

这是我试图从.js文件中点击的url,该文件包含与敲除相关的函数:

self.followAction=$.resolvePath("/Peoples/Follow?uid="+data.UserId);这里People是控制器,Follow是操作方法,点击按钮,我想发送userId,所以我写了这个。

为了从javascript中解析相对路径,我编写了以下函数

// Fix for resolving relative paths from within js scripts
$.resolvePath = function(url)
{
var path = '@Request.ApplicationPath';
if (path != '/') return path + url;
 return url;
};

但是,点击按钮,我得到了这个错误:HTTP错误404.0-找不到它正在尝试的url是:

localhost:44305/People/@Request.ApplicationPath/People/Follow?uid=8

我已经知道,在js文件中不会解释razor代码。所以,我把这个函数放在一个局部视图中:

   $.resolvePath = function(url)
    {
      var path = '@Request.ApplicationPath';
      if (path != '/') return path + url;
       return url;
     };

我试着在布局头的部分直接调用它,如下所示:

 <head>
 <script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
 @{ Html.RenderPartial("VirtualPathFix"); }
 </head>

但随后错误开始显示:

 $.resolveurl: function is not defined

如果我把这个函数直接放在scripts文件夹中的people.js文件中,那么没有错误,但点击follow按钮,传递url的http 404错误是:

 localhost:44305/People/@Request.ApplicationPath/People/Follow?uid=8

有人能帮我吗?寻找丢失的

我已经尝试在查看页面的标题中使用window.baseUrl,这是darin:建议的

   <script type="text/javascript">
    window.baseUrl = '@Url.Content("~/")';
   </script>

但是我的people.js文件无法获取此属性,因此错误为:

Uncaught TypeError: window.baseUrl is not a function on line18 in people.js file. Can anyone tell me what are other things to try.

您可以在Razor模板中准备此url:

<head>
    <script type="text/javascript">
       window.baseUrl = '@Url.Content("~/")';
    </script>
</head>

现在,在您的js文件中,您可以使用这个变量window.baseUrl。您不再需要这个$.resolvePath函数。