Say I have the site http://localhost/virtual where virtual is the virtual directory
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?
Aku's hint above looked right but it didn't want to work for me. Finally I figured out to 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.
Another way to get a base url is
For example, if you run your app from SomeName virtual directory then window.g_baseUrl variable will be equal to /SomeName/
Benefit of this method is an ability to call actions in the other controllers like so
$.getJSON(window.g_baseUrl + "AnotherController/Action")
I used this solution successfully
Place the following element in your masterpage
<%= Html.Hidden("HiddenCurrentUrl", Url.Action("Dummy"))%>
var baseUrl = "";
baseUrl = $("#HiddenCurrentUrl").val(); baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));
$.getJSON(baseUrl + "Action")
EDIT Improved solution
In your controller
ViewBag.BaseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/";
In your master page
Use your baseUrl
$.getJSON(YourNameSpace.config.baseUrl + "Action")
It is too late to answer this question. But may be useful to someone as I had same problem. Instead of doing all this steps mentioned in above answers, better way is to use
It'll generate url
/VIRDIR/controller/action if it is running from virtual directory or generate
/controller/action in other case.
Relative Path to the JS file was the only solution I found $.getJSON("../Controller/Action")
~ as you can see.
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');