Reputation: 191
I followed a tutorial and wanted to expand the functionality of already existing code. Code: https://send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA
It's using angularJS as the frontend and webapi 2 aspnet with entitiyframework. The problem is that my http posts are sending null values. I am guessing I have to post it in the right format, but im not sure how exactly to do it.
I tried transforming it into an object but it still received as null.
controller.js
function save(contact) {
var deferred = $q.defer();
$http.post('/api/Contact/' + contact).success(function (results) {
$scope.contact = results;
deferred.resolve(results);
}).error(function (data, status, headers, config) {
deferred.reject('Failed saving contact');
});
return deferred.promise;
};
fails at db.Contacts.Add(Contact); (null error)
public HttpResponseMessage Post([FromBody] Contact Contact)
{
if (ModelState.IsValid)
{
Console.Write("post contact");
Console.Write(Contact);
db.Contacts.Add(Contact);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Contact);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Contact.Id }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
Tried sending this:
{Name: "test", Address: "test", City: "teee", Country: "tesd"}
Edit:
After trying to save the contact with the save
function:
output of console log Request URL: http://localhost:64158/api/Contact/[object%20Object]
If i open the [object%20Object] in a new tab from the network view i get this:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'SampleEF6.Models.Contact Get(Int32)' in 'SampleEF6.Controllers.ContactController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
Upvotes: 1
Views: 342
Reputation: 166
You're sending the data wrong. You're supposed to send the data (contact in this example) in the body of the request, instead of the url.
Try $http.post('/api/Contact/', contact)
https://docs.angularjs.org/api/ng/service/$http#post
Upvotes: 3