I'm using an AngularJS $resource to contact MVC ActionMethods on the server. The resource URL is /api/customer, so for the $resource.query function I provide an ActionMethod called Customer on the ApiController. This works fine.
Now I want to provide an ActionMethod for $resource.save.
Obviously, the 2nd ActionMethod needs the same name, but since neither ActionMethod has any parameters this is not allowed.
What is the best practice for this situation? Should I stay away from server side MVC for AngularJS projects?
Thanks in advance.
-
I have found that I can use parameters to change the url so that it contains the name of the appropriate ActionMethod. However, I don't know if this is the ideal approach. It feels a little dirty to me.Bobbler– Bobbler2014-05-05 12:36:20 +00:00Commented May 5, 2014 at 12:36
-
Are you using Web API or not? It's a completely separate thing from MVC, you don't necessarily want to add a dependency to it just to solve a problem that could quite easily be done with MVC alone. I guess more generally: do you really want to expose an API, or are you just doing it so you can use Angular?Ben Aaronson– Ben Aaronson2014-05-14 20:53:56 +00:00Commented May 14, 2014 at 20:53
-
I wasn't using WebAPI when I asked the question but I am now and it solves my problem (see next answer and comments). I think I could do it in ASP.NET MVC by deriving from ApiController and setting up some ApiRoutes but I haven't confirmed that. Yes, this is just so I can use AngularJS, specifically to create a single page app. If there is an ideal recommendation for this I'd still like to hear it. Thanks.Bobbler– Bobbler2014-05-15 07:20:14 +00:00Commented May 15, 2014 at 7:20
2 Answers
You should create a controller CustomerController deriving from ApiController. Then the methods
Get(int id) works for getting customer with specific id. Url: api/customer/1
Delete(int id) works for deleting customer with specific id. Url: api/customer/1
3 Comments
Further to my comment, I am adding this answer in case someone finds it helpful. It solves my original problem but I don't know if it's the best solution.
Original factory:
app.factory("customerResource", function ($resource) {
var customerResource = $resource("/api/customer/:id", { id: "@id" });
return customerResource;
});
Original line in controller:
$scope.customers = customerResource.query();
Amended factory:
app.factory("customerResource", function ($resource) {
var customerResource = $resource("/api/:action/:id", { id: "@id", action: "@action" });
return customerResource;
});
Amended line in controller:
$scope.customers = customerResource.query({action: "get");
Now I can use other $resource functions using a different action, like so:
drawing.$remove({action: "delete"});
These calls will reach the Get and Delete ActionMethods on the ASP.MVC server.