I am using angular with MVC4. I would like to call a MVC controller method from javascript using $http.get(). It requires a url (obviously). I would like this to be a relative path, but how do I write that? My controller is in Controllers/Api/ExampleController. I would like the path to resolve even if I move the javascript file into another location, meaning I would like the path to be relative to application root as opposed to the javascript file. I Have tried "~/Controllers/Api/ExampleControllerMethod" and "Controllers/Api/ExampleController/Method.
Asked
Active
Viewed 1.2k times
4
-
It would be better if you show your directory structure. Have you tried using "/Controllers/Api/ExampleControllerMethod" ? – Kuldeep Daftary Jan 09 '14 at 12:07
-
No I haven't tried that. The controller directory is in the root of my web application. – Shumii Jan 09 '14 at 12:50
-
"/Controllers/Api/ExampleControllerMethod" should work! – Kuldeep Daftary Jan 09 '14 at 13:07
-
No that doesn't work - and also how would it work not knowing what controller to go to? – Shumii Jan 10 '14 at 17:06
3 Answers
3
The $location
service does provide information from the url. So, you could construct something to then make the host and port dynamic:
var url = $location.host() + '/Controllers/Api/ExampleControllerMethod';
From the documentation:
**url: http://www.example.com/base/path?a=b#h**
$location.protocol() = http
$location.host() = www.example.com
$location.port() = 80
$location.path() = /path
$location.search() = {"a":"b"}
$location.hash() = h

Davin Tryon
- 66,517
- 15
- 143
- 132
1
Thanks for the ideas but this kind of thing is what I was looking for:
Configure the WebApiConfig to add a route like so (should have it as default):
config.Routes.MapHttpRoute(
name: "ApiMethods",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
So now I can go $http.get('api/{controller}/{method}')

Shumii
- 4,529
- 5
- 32
- 41
-
I was doing the mistake of having $http.get('/api/v1/...') .. The first slash was unnecessary and after changing to $http.get('api/v1/...') it worked. There was no need for $location – Rashmi Pandit Feb 23 '16 at 02:28
1
What worked for me was to provide the Url as "/ControllerName/Action" (instead of "ControllerName/Action")

Shawn de Wet
- 5,642
- 6
- 57
- 88