5

I'm trying to make an ajax call like so:

 $.get('/home/myInfo', function (data)

     {

        ....

     });

I'm calling it from a page that is at: http://localhost/myapp/home/index

When I try to make the above call, it goes to: http://localhost/myapp/home/index/home/myInfo

I want it to go to http://localhost/myapp/home/myInfo

Do I have to specify absolute URL?

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

2 Answers2

14

Absolutely never hardcode urls like this in an ASP.NET MVC application. Always use URL helpers when dealing with urls, like this:

$.get('@Url.Action("MyInfo", "Home")', function (data) {
    ....
});

or if this is in a separate javascript file where you cannot use server side helpers, well you could for example use HTML 5 data-* attributes on some DOM element tat you are AJAXifying, like a div or something:

<div id="mydiv" data-url="@Url.Action("MyInfo", "Home")">Click me</div>

and then:

$('#mydiv').click(function() {
    $.get($(this).data('url'), function (data) {
        ....
    });
});

or if you are AJAXifying a form or an anchor:

$('#myanchor').click(function() {
    $.get(this.href, function (data) {
        ....
    });
    return false;
});

where the anchor would of course have been generated using helpers:

@Html.ActionLink("click me", "MyInfo", "Home", null, new { id = "myanchor" })

See? No need to hardcode urls. Don't do it as it will break at the very second you modify the pattern of your routes in Global.asax. By following this technique your code will be totally agnostic to any changes of the structure of your routes.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Ah yes, I knew there must be a better way. Thank you. – dev.e.loper Sep 20 '11 at 21:40
  • 3
    Any reason for the downvote? Please leave a comment when downvoting explaining the reasoning behind it. – Darin Dimitrov Sep 20 '11 at 21:43
  • 1
    WRT hardcoding URLs: It always frustrates me that OOB helper methods are not intellisense-aware. "MyInfo" & "Home" are always magic strings. ReSharper helps with this, but still leaves potential to have unbounded action urls – JoeBrockhaus Nov 24 '14 at 20:20
0

Are you sure you have copied and pasted the code correctly? Because as you have it, that should be referencing http://localhost/home/myInfo . The only reason I could see it doing as you have described is if your code was using a relative url like this:

 $.get('home/myInfo', function (data)

     {

        ....

     });

Otherwise, if you're truly using the value "/home/myInfo" instead of "home/myInfo" , you already are referencing the absolute version of the url (the definition of an "absolute" url being that it starts with "/"). I ran some quick tests, and on my local machine, using "/home/myInfo" yields an XHR request to http://localhost/home/myInfo

streetlogics
  • 4,640
  • 33
  • 33