码迷,mamicode.com
首页 > 编程语言 > 详细

ResolveUrl in external JavaScript file in asp.net project

时间:2018-07-12 20:14:01      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:htm   with   ret   problem   for   lock   http   mvc   overflow   

https://stackoverflow.com/questions/11263425/page-resolveurl-is-not-working-in-javascript

The problem, as poncha pointed out, is that as far as ASP.NET is concerned, the content delivered in your .js file is a string. It does not apply any sort of rendering before IIS delivers it. It gets the same treatment any other content file would, like a .jpg or .png.

In order to call server side methods (like ResolveUrl), you need to use the <% ... %> syntax within any page that is parsed by ASP.NET (like an .aspx or .master file).


By the way, these little code blocks go by a lot of different names:


In particular, we want a Displaying Expression with the syntax <%= ... %>, where:

the value that is entered after the equals sign is written into the current page

Knowing that, we can build our own own URL by using ResolveClientUrl() which:

returns a URL string suitable for use by the client to access resources on the Web server

To this, we‘ll pass in the Web Application Root Operator or ~ character, where ASP.NET:

resolves the ~ operator to the root of the current application:

By combining these, we can save the result of the displaying expression into a JavaScript variable by placing the following code on your Master Page (adapted from Joel Varty‘s blog):

The following script should place before the external JavaScript reference

<script type="text/javascript">
    var baseUrl = ‘<%= Page.ResolveClientUrl("~/") %>‘;
</script>

Since JavaScript variables are inherently global, any other script can now access the baseUrl variable, so we can utilize it from the .js file with the following script:

function ResolveUrl(url) {
    return url.replace("~/", baseUrl);
}

Now you can call ResolveUrl("~/DynamicMenu.ashx") directly from your javascript file and it will create the appropriate URL by stripping out "~/" and replacing it with the baseUrl created earlier by the server side script.


Further Reading:

 

ResolveUrl in external JavaScript file in asp.net project

标签:htm   with   ret   problem   for   lock   http   mvc   overflow   

原文地址:https://www.cnblogs.com/chucklu/p/9300948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!