Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
Dan Avatar asked Jan 22 '10 11:01

Dan


4 Answers

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.

like image 91
Jesse B. Avatar answered Oct 19 '22 06:10

Jesse B.


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")

EDIT Improved solution

In your controller

ViewBag.BaseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/";

In your master page

<script type="text/javascript">
    var YourNameSpace = YourNameSpace || {};
    YourNameSpace.config = {
        baseUrl: "@ViewBag.BaseUrl"
    }
</script> 

Use your baseUrl

$.getJSON(YourNameSpace.config.baseUrl + "Action")
like image 29
Andreas Avatar answered Oct 19 '22 06:10

Andreas


Another way to get a base url is

<script type="text/javascript">
  window.g_baseUrl = '@Url.Content("~")';
</script>

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") 
like image 4
aku Avatar answered Oct 19 '22 06:10

aku


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

like image 2
Anton Gogolev Avatar answered Oct 19 '22 04:10

Anton Gogolev