MVC3 相对 URL 路径 - Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5889797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:41:46  来源:igfitidea点击:

MVC3 Relative URL Paths - Javascript

javascriptasp.net-mvc-3urlpathrelative-path

提问by fes

I have an issue with relative paths whereby when the web app is running off subdirectory of the domain, the paths are not correct. e.g. http://www.example.com/webapp/

我有一个相对路径问题,即当 Web 应用程序在域的子目录之外运行时,路径不正确。例如http://www.example.com/webapp/

If I use @Url.Content("~/path/to/action")on the page it is fine. I can even embed the @Url.Content("")inside the javascript script. I want to clean up the page I wanted to put the javascript inside a js file and reference that. Now that the @Url.Contentis being called inside the javascript file, it doesn't seem to work (probably for obvious reasons). How can I get around this issue?

如果我@Url.Content("~/path/to/action")在页面上使用它就可以了。我什至可以将其嵌入@Url.Content("")到 javascript 脚本中。我想清理我想将 javascript 放在 js 文件中并引用它的页面。现在@Url.Content正在 javascript 文件中调用它,它似乎不起作用(可能出于明显的原因)。我怎样才能解决这个问题?

I had a look at the <base />but that doesn't seem to work.

我看了看,<base />但这似乎不起作用。

回答by counsellorben

Now that you moved everything into a separate js file, the file is being served as static content, and the Razor syntax is not being parsed.

现在您已将所有内容移动到一个单独的 js 文件中,该文件将作为静态内容提供,并且不会解析 Razor 语法。

If you need relative paths inside of your js which might change, then you should include a script in each page which sets a path var, and use @Url.Content(...) in this script, e.g.,

如果你需要在你的 js 中的相对路径可能会改变,那么你应该在每个页面中包含一个设置路径变量的脚本,并在这个脚本中使用 @Url.Content(...) ,例如,

<script type="text/javascript">
    pathToAction = "@Url.Content(...)";
</script>

Then, declare the pathToAction var in your js file, and use it as needed.

然后,在您的 js 文件中声明 pathToAction 变量,并根据需要使用它。