Search code examples
javascriptjqueryasp.net-mvcvirtual-directory

Javascript in Virtual Directory unaware of Virtual Directory


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?


Solution

  • Aku's hint above looked right but it didn't want to work for me. Finally I figured out to use it like this

    <script type="text/javascript">
        var config = {
            contextPath: '<%= @Url.Content("~")  %>'
        };
    </script>
    

    and then in my JavaScript I use it like this

    config.contextPath + 'myAppPath".

    So in case of no virtual directory this resolves to "/" + "myAppPath" and in case of a virtual directory this resolves to "/VirtualPath/" + + "myAppPath"

    and this finally worked for me.