在外部js文件中,我不能使用
url = "@Url.Action("Action", "Controller")"
//url output : @Url.Action("Action", "Controller")
//I get IllegalPath Name error.
当我这样写的时候:
url = "/Controller/Action"
如果项目在子文件夹下,则脚本不起作用。我需要类似这样的内容作为相对Url:
url = "~/Controller/Action"
ı如何做到这一点呢?谢谢。
发布于 2012-11-30 16:04:40
由于asp.net mvc视图引擎无法解析.js文件,因此您不能在其中使用任何c#代码。我建议使用不显眼的方法,就像这样
<div id="loader" data-request-url="@Url.Action("Action", "Controller")"></div>
在javascript中,使用data-request-url
的值
$(function(){
$('#loader').click(function(){
var url = $(this).data('request-url');
alert(url);
});
});
发布于 2012-11-30 15:16:39
我不确定这是否是最优雅的解决方案,但我所做的是区分寄存器和外部脚本中的实际实现,以便:
<script>...</script>
... include all the external scripts I need
$(document).ready(function(){
//get all the information you need from your MVC context
//before going out of context and into the scripts
var url = '@Url.Action("Action", "Controller")';
RegisterMyFunction(url, other parameters ..);
RegisterAnotherFunction(url, others...);
}
因此,在我的视图中,只有寄存器函数和脚本包含作为参数的特殊值,以执行任何我想做的事情。
希望能有所帮助,
发布于 2017-12-06 05:58:23
这是我一直在使用的模式。这需要更多的步骤,但我喜欢我的所有urls都在视图中的一个有组织的位置。
在我的视图底部,我将包括一个脚本部分,其中包含urls,如下所示:
@section Scripts
{
<script type="text/javascript">
myJavaScriptObject.firstUrl = '@Url.Action("Action1", "Controller", new {id = Model.Id})';
myJavaScriptObject.secondUrl = '@Url.Action("Action2", "Controller", new {id = Model.Id})';
</script>
}
在我的JavaScript类(在外部文件中)中,我将像这样引用url:
var myJavaScriptObject = {
firstUrl: '',
secondUrl: '',
docReady: function() {
$.get(myJavaScriptObject.firstUrl, function(data) { do something... });
}
}
我意识到这些条目不需要在类中引用,但我喜欢把它们放在那里作为我自己的内部管理。
https://stackoverflow.com/questions/13640559
复制相似问题