开发者

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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜