ResolveUrl in external JavaScript file in asp.net project
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:
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-07-12 字符编码
2015-07-12 Which are in?
2015-07-12 IQ Test
2015-07-12 string.Split函数