Dann Dann - 5 months ago 11x
Javascript Question

Javascript in Virtual Directory unaware of Virtual Directory

Say I have the site
where virtual is the virtual directory

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


When this is called, the client tries to find the url at the root level i.e.

If I add the tilde (~) symbol in, it turns into

It should (if it was to do what I wanted) resolve to

Any ideas on how to fix this?


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"

Use your baseUrl

$.getJSON(YourNameSpace.config.baseUrl + "Action")