简体   繁体   English

在ASP.NET MVC中使用外部JavaScript文件

[英]Using external javascript files with asp.net MVC

I have some javascript inwhich I am using such helpers as 我有一些JavaScript,其中我正在使用诸如

var url = <%=ResolveUrl("~/controller/action") %> 

When the javascript is embeded in the .aspx page using the 使用以下命令将javascript嵌入.aspx页中时:

<script> tag everything works fine <script>标记一切正常

When I move it out to an external file those scripts that have the helper methods do not work. 当我将其移至外部文件时,具有帮助程序方法的那些脚本不起作用。

Other scripts do just the ones with the 其他脚本仅使用

var url = <%=ResolveUrl("~/controller/action") %>

do not. 不要。

Are these not possible to use in external javascript files?? 这些不能在外部javascript文件中使用吗?

I would like to get all of my javascript out of the aspx files if I can. 如果可以的话,我想从aspx文件中获取所有JavaScript。

thanks! 谢谢!

ResolveUrl is a helper method of the Control class which is why you are able to call them from ViewPages (ending in .aspx) ResolveUrl是Control类的帮助器方法,这就是为什么您可以从ViewPages中调用它们的原因(以.aspx结尾)

You can't call these from javascript because those files are treated as simple assets with no compilation. 您无法从javascript调用这些文件,因为这些文件被视为没有编译的简单资产。

What you can do, however, is set variables for those paths you need in the master page or view page and reference them from the js files. 但是,您可以做的是在母版页或视图页中为所需的路径设置变量,并从js文件中引用它们。 An even better solution is to keep the URLs you need in the document, such as in <a> tags and use javascript to fish them out whenever actions are performed: 一个更好的解决方案是将您需要的URL保留在文档中,例如<a>标记中,并在执行操作时使用javascript将它们引出:

For instance, this jquery code fetches the url from an <a> tag and replaces the tag with the html content from an ajax call. 例如,此jquery代码从<a>标签获取url,并用ajax调用中的html内容替换该标签。

$('a#clickme').click(function() {
    var $this = $(this);
    $.ajax({
        type: 'GET',
        url: $this.attr('href'),
        success: function(data) {
            $this.replaceWith(data);
        },
        failure: function(data) {
            alert('Handle this error gracefully');
        }
    });
    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM