Reputation: 2199
I am using web api in my mvc application. I have a problem while calling web api using jquey.get function. Consider the following scenario:
I have 2 controller name:
HomeMVC controller contains 2 actions
TestAPI controller contains 1 action
When i was on Index view of HomeMVC controller i.e.
http://localhost:1025/Home
and when i call $.get("api/TestAPI/Get")
from the browser it returns the expected json response.
But when i was on About view of HomeMVC controller i.e.
http://localhost:1025/Home/About
and when i call $.get("api/TestAPI/Get")
from the browser it returns error, resource not found, and the resource it is trying to locate is:
http://localhost:1025/Home/About/api/TestAPI/Get
instead of
http://localhost:1025/api/TestAPI/Get
Why browser added Home/About in the url to api and why it is not added Home/Index when i was on Index view. On Index view why api call is working as expected and why not working on About view ??
Upvotes: 0
Views: 137
Reputation: 4886
You used a relative url when you should be using an absolute url.
You should instead use an absolute url by doing:
$.get("@Url.RouteUrl("@Url.RouteUrl("DefaultApi", new {httproute="", controller="TestAPI", action="Get"}))
If you want to keep your javascript in separate js files (and not in the razor files) what you can do is have an initialize method that is called from a razor view.
The .js file:
var myPageJsUrls = {};
var MyPageInitialize = function(getItemsUrl, saveItemUrl, editItemUrl){
myPageJsUrls.getItemsUrl = getItemsUrl;
myPageJsUrls.saveItemUrl = saveItemUrl;
myPageJsUrls.editItemUrl = editItemUrl;
}
var getItems = function(){
return $.get(myPageUrls.getItemsUrl);
}
...
In the razor file:
<script>
myPageInitialize('@Url.Action("AllItems", "Items")', '@Url.RouteUrl("DefaultApi", new {httproute="", controller="TestAPI"}, ...)
</script>
Upvotes: 1