Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use Relative URL in Ajax Post in MVC3

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.

like image 991
3lokh Avatar asked Apr 25 '12 16:04

3lokh


2 Answers

Description

You should use the Url.Action method. But in your case, a seperate js file, you cant access this method. So i would create a javascript variable for each url in your view. Then you can use this variable in your js file.

UrlHelper.Action Method - Generates a fully qualified URL to an action method.

Sample

Your View

<script type="text/javascript">
    var myUrl = '@Url.Action("actionName", "controllerName")';
</script>

<script type="text/javascript" src="yourJsFile.js"/>

Your js file

$.ajax({
       url: myUrl,
       ....
})

Update

Another way is to store your url in a hidden field inside your view and get the hidden fields value inside your js file.

More Information

  • MSDN - UrlHelper.Action Method
like image 145
dknaack Avatar answered Sep 25 '22 14:09

dknaack


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.

like image 43
3lokh Avatar answered Sep 24 '22 14:09

3lokh