简体   繁体   中英

Using external javascript files with asp.net MVC

I have some javascript inwhich I am using such helpers as

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

When the javascript is embeded in the .aspx page using the

<script> tag everything works fine

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??

I would like to get all of my javascript out of the aspx files if I can.

thanks!

ResolveUrl is a helper method of the Control class which is why you are able to call them from ViewPages (ending in .aspx)

You can't call these from javascript because those files are treated as simple assets with no compilation.

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. 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:

For instance, this jquery code fetches the url from an <a> tag and replaces the tag with the html content from an ajax call.

$('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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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