views:

194

answers:

4

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?

+2  A: 

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

Anton Gogolev
No, it just adds to the Path. It might work if the js file was in the root.
burnt_hand
A: 

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');
bobince
A: 

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

burnt_hand
A: 

I used this solution successfully

Place the following element in your masterpage

<%= Html.Hidden("HiddenCurrentUrl", Url.Action("Dummy"))%>

Declare a global variable in your main javascript file

var baseUrl = "";

Set baseUrl to the value of "HiddenCurrentUrl" when your javascript is loaded

baseUrl = $("#HiddenCurrentUrl").val();
baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));

Use baseUrl

$.getJSON(baseUrl + "Action")
Andreas
I am marking this as the answer as it is funky, and I like funky mixes of jQuery and MVC. Although I might use something diff to using Url.Action as the substring thing isn't so clean
burnt_hand
Great that you found this helpful! I'm not satisfied with the Url.Action solution so please tell me how you end up solving it. I hate URL stuff. Always problems between dev/test/prod environments.
Andreas