HaukurHaf
HaukurHaf

Reputation: 13796

AngularJS resource and put method

OK, I've been battling with this for a few hours now. I'm using .NET Web API as a backend and I must admit I do not fully understand how this thing works. I find the REST api to be very implicit and when things work, they do because of some magic, that is, because the function name starts with Get, then that happens etc. etc.

Here's what I'm trying to do:

In my Web API controller (NotesController) I have this method:

public HttpResponseMessage Put(string date, string notes)

It receives a date in the format yyyy-MM-dd and some arbitrary text.

I've declared my resource in Angular in this way as it stands now:

App.factory('NotesFactory', function ($resource) {
    return $resource('/api/Notes/', {}, { update: { method: 'PUT' } });
});

Lastly, I have a saveNotes() method on my Angular notes controller, like this:

$scope.saveNotes = function ()
{
    NotesFactory.update({ date: date, notes: $scope.notes }, function () {
    ...
    });
}

I'm having problems getting the update() method to correctly call the Put() method in my Web API.

The error I receive is:

"No action was found on the controller 'Notes' that matches the request"

As I said, I'm not sure how this is exactly supposed to work. Would be really glad if someone could provide a concrete example that works for my situation. I've already been reading the $resource documentation back and forth to no avail.

Any takers? :-)

Upvotes: 1

Views: 3994

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

angular will pass your request as JSON inside of the body:

{ 
"date": "2013-06-03", 
"notes": "My notes" 
}

So the most suitable would be to create an object representing these values:

public class MyObject
{
    public DateTime Date { get; set; }
    public string Notes { get; set; }
}

And then adjust the method signature

public HttpResponseMessage Put(MyObject obj)

The Web API will deserialize the content of the message (JSON in the body) and create an instance of MyObject. The signature with simple types would be useful in cases, when these parameters are part of the URL. Try this reading for more details http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

Upvotes: 1

Related Questions