Javascript in Virtual Directory unaware of Virtual Directory

Viewed 17935

Say I have the site http://localhost/virtual where virtual is the virtual directory

I have an Ajax request that is defined in a javascript file using JQuery

$.getJSON("/Controller/Action")

When this is called, the client tries to find the url at the root level i.e. http://localhost/Controller/Action

If I add the tilde (~) symbol in, it turns into http://localhost/virtual/~/Controller/Action

It should (if it was to do what I wanted) resolve to http://localhost/virtual/Controller/Action

Any ideas on how to fix this?

8 Answers

Maybe,$.getJSON("Controller/Action") will do?

The tilde shortcut for your application root path is a special feature of ASP.NET, not part of URLs themselves. Consequently trying to use a URL with a tilde in from JavaScript won't resolve the site root, it'll just give you a literal ~ as you can see.

You'd need to pass the value of the application root path to JavaScript so it can construct URLs itself. I'm not that familiar with ASP.NET but I believe you could do something like:

<script type="text/javscript">
    var approot= <%= JavaScriptSerializer.Serialize(Request.ApplicationPath) %>;
    ... $.getJSON(approot+'/Controller/Action') ...;
</script>

A simpler way to do it if you know there's a link on the page to the approot would be to read the href of that link:

var approot= $('#homepagelink').attr('href');

Relative Path to the JS file was the only solution I found $.getJSON("../Controller/Action")

Related