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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With