How to Use Relative URL in Ajax Post in MVC3

ajax, asp.net-mvc-3, post, relative-path

Solution

I finally found a partial work around. In my .js file i did some dirty coding like this:

 var Path = location.host;
 var VirtualDirectory;
 if (Path.indexOf("localhost") >= 0 && Path.indexOf(":") >= 0) {
 VirtualDirectory = "";

 }
 else {
 var pathname = window.location.pathname;
 var VirtualDir = pathname.split('/');
 VirtualDirectory = VirtualDir[1];
 VirtualDirectory = '/' + VirtualDirectory;
 }
$.ajax({
   url: VirtualDirectory/Controller/Action,
   ....})

The basic idea is I check the URL for localhost and port number. If both are there, it means that then I'm debugging in my local machine and so I don't need virtualdirectory in URL. If I'm running a hosted version then there won't be localhost and port number in my URL(provided I'm hosting on port 80).

And by this way when I run on my local machine while debugging the url will be only Controller/Action and while I host the URL will be VirtualDirectory/Action/Controller. It works fine for me now.

But please post if there is any other simple method.

Problem

I have an Ajax post call written in a separate ".js" file which I call in multiple pages. My code looks like this: ``` $.ajax({ url: '/MyVirtualDirectory/Controller/Action', type: 'POST', dataType: 'json', .... .... }) ``` Each time I change my virtual directory in my server, I'm required to change the code in "URL" to make my Ajax call working. Is there any method that can make my code independent of my "Virtual Directory" name in IIS ..? My application is MVC3.

Original source