Vijay V
Vijay V

Reputation: 389

JQuery "Get" not getting absolute path in MVC4

On my dev box the URL to my site is "http://localhost:portname/home" and when I click on the "Hello " on the top right side after logging in, the path it takes me to is "localhost:­/­Account/­GetTabContent/tab1"

using the following jQuery code:

var url = "/Account/GetTabContent/tab1";
var targetDiv = $('#div1');
$.get(url, null, function (result) {
  $(targetDiv).html(result);
});

This works fine on my box. However when we deploy it to our test server the actual website's path is:

http://server name/website folder/home

Now when I click on the Name after logging in it still takes me to

http://server name/Account/GetTabContent/tab1

and I get a 404 error. How do I force it to go to

http://server name/website folder/GetTabContent/tab1

I hope my question makes sense. Please let me know if it doesnt and I will clarify

****EDIT*****

ok we fixed the problem by changing the following code (removed the controller name from the url, wonder how this will be when calling another controller's action)

**var url = "GetTabContent/tab1";**
var targetDiv = $('#div1');
$.get(url, null, function (result) {
$(targetDiv).html(result);
});

Upvotes: 0

Views: 708

Answers (2)

Mirko
Mirko

Reputation: 4282

Generally I would recommend to set the path using the Url Helpers, so in your code above do this instead:


var url = '@Url.Action("GetTabContent", "Account", new { id = "tab1" })';
var targetDiv = $('#div1');
$.get(url, null, function (result) {
  $(targetDiv).html(result);
});

In places where urls are accepted (such as script tags etc), specify your urls with the tilde, so e.g.:


<script src="~/Scripts/foo.js"></script>

(this presume MVC 4, but since that is tagged I figured this seems fair :))

instead of specifying relative or worse absolute paths to a location that you may want to change at deployment time.

Upvotes: 1

Clark T.
Clark T.

Reputation: 1470

I have the same issue on a lot of frameworks my solution is to set the action of the form to where i want it to go as the mvc usually uses something similar to echo Form:open('action'); which kicks out an absolute path bear in mind this is on a php framework but id assume asp ones offer something similar so with my jquery i use

$.post($(this).attr('action'), $(this).serialize(), function and so on

Upvotes: 0

Related Questions