Https://stackoverflow.com/questions/11263425/page-resolveurl-is-not-working-in-javascript
The problem, as Poncha pointed out, are the as far as ASP. Concerned, the content delivered in your. js fil E is a string. It does not apply any sort of rendering before IIS delivers it. It gets the same treatment any and content file would, like a .jpg
or .png
.
In order to call server side methods ( ResolveUrl
as), you need to use the <% ... %>
syntax within any page this is parsed by ASP (like a .aspx
or .master
file).
By the the-by, these little code blocks go-a lot of different names:
- Inline Expressions
- Embedded Code Blocks
- Code Nuggets
- Server Side Script Delimiters
- Code Render Blocks
- ASP directives
In particular, we want a Displaying Expression <%= ... %>
with the syntax, where:
The value of is entered after the equals sign was written into the current page
Knowing that, we can build our own own URLs 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:
Resolves the ~ operator to the root of the current application:
By combining these, we can save the result of the displaying expression to a JavaScript variable by placing the Followin G 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 is inherently global, any other script can now access baseUrl
the variable, so we can utilize it From the. js file with the following script:
function ResolveUrl(url) { return url.replace("~/", baseUrl);}
Now your can call ResolveUrl("~/DynamicMenu.ashx")
directly from your JavaScript file and it'll create the appropriate URL by stripping out "~/" and Replacing it with the BASEURL created earlier by the server side script.
Further Reading:
- What is the difference between RESOLVEURL and Resolveclienturl?
- Relative Urls
RESOLVEURL in external JavaScript file in ASP.