javascript 使用单独的 js 文件并在其中使用 Url Helpers 和 ASP.NEt MVC 3 和 Razor View Engine
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9922041/
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
Use Separate js File And use Url Helpers in it with ASP.NEt MVC 3 and Razor View Engine
提问by Saeid
I ask a similar question hereand Darin Dimitrov
answer that we can't use Url helper like $.ajax({ url: '@Url.Action("Index")', . . .
in separate js file so what is your suggestion to use Url helper in view page and pass it to javascript, I don't want to use hard code url, I need to find it with Url helper.?
我在这里问了一个类似的问题,并Darin Dimitrov
回答说我们不能像$.ajax({ url: '@Url.Action("Index")', . . .
在单独的 js 文件中那样使用 Url 助手,那么您对在视图页面中使用 Url 助手并将其传递给 javascript 的建议是什么,我不想使用硬编码的 url,我需要使用 Url helper 找到它。?
回答by raklos
Use a hidden field to store your url, then use javascript to read the hidden field, then use that in your code. That way you can keep the JS file separate to the view. Something like this:
使用隐藏字段来存储您的 url,然后使用 javascript 读取隐藏字段,然后在您的代码中使用它。这样您就可以将 JS 文件与视图分开。像这样的东西:
//In Your View
@Html.Hidden("MyURL", Url.Action("Index"))
//In Your JS
var myUrl = $("#MyURL").val();
$.ajax({ url: myUrl , . . .
回答by Simon Edstr?m
The easiest way is just to create a global variable called something and just reference to it in your external JS
最简单的方法是创建一个名为 something 的全局变量,然后在外部 JS 中引用它
var baseURL = '@Url.Action("Index")';
Inside your external JS
在您的外部 JS 中
$.ajax({ url: baseURL + "Action"
回答by tpeczek
回答by Shakil Makani
There is no need to have hidden field, even this works too in the external .js file.
不需要隐藏字段,即使这也适用于外部 .js 文件。
var myUrl = /ControllerName/ActionName;
var myUrl = /ControllerName/ActionName;
$.ajax({ url: myUrl , . .
回答by Mike Rivet
I used a similar approach to raklos, but was looking to get the root directory path in all places, so I went with the code below.
我使用了与 raklos 类似的方法,但希望在所有位置获取根目录路径,因此我使用了下面的代码。
@Html.Hidden("AppUrl", Url.Content("~"))
回答by Marius Schulz
Take a look at Generating External JavaScript Files Using Partial Razor Views. In this blog post, I describe how you can make use of regular Razor views and a custom action filter to render external JavaScript files that can have Razor code in them.
查看使用部分 Razor 视图生成外部 JavaScript 文件。在这篇博文中,我描述了如何使用常规 Razor 视图和自定义操作过滤器来呈现可以包含 Razor 代码的外部 JavaScript 文件。