Reputation: 547
I have an angular post method through which I want to pass data to web api post but doesn't seem to work. What could I be doing wrong?
customerPersistenceService.js
var customerPersistenceService = function ($http, $q) {
return {
save: function(customer) {
var deferred = $q.defer();
$http.post("/api/customers", customer)
.success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
update: function(customer) {
var deferred = $q.defer();
$http.put("/api/customers/{id}" + customer.id, customer)
.success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
}
};
};
customerEditCtrl.js
function customerEditCtr($stateParams, $location, customerPersistenceService) {
var vm = this;
vm.editableCustomer = {};
vm.selectedCustomerId = $stateParams.id;
customerPersistenceService.getById(vm.selectedCustomerId).then(
function (customer) {
vm.editableCustomer = customer;
});
};
vm.saveCommand = function () {
if (saveCustomer) {
var customer = vm.editableCustomer;
customer.id = vm.selectedCustomerId;
if (customer.id !== 0) {
customerPersistenceService.update(customer).then(
function (result) {
return result.data;
});
} else {
customerPersistenceService.save(customer).then(
function (result) {
return result.data;
});
}
}
};
};
In the CustomerAPIController.cs my methods look like these:
[HttpPost]
public HttpResponseMessage Post([FromBody]Customer newCustomer)
{
try
{
if (ModelState.IsValid)
{
_customerService.AddNewCustomer(newCustomer);
return Request.CreateResponse(HttpStatusCode.Created, newCustomer);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
[HttpPut]
public HttpResponseMessage Put(int id, [FromBody]Customer editableCustomer)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
if (id != editableCustomer.Id)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
try
{
_customerService.UpdateCustomer(editableCustomer);
return Request.CreateResponse(HttpStatusCode.OK, "{success:'true', verb:'PUT'}");
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
Update: After some investigation, I realise the vm.editableCustomer seems to contain an array of all customer objects making it hard to pass to the Web API POST. I fail to understand how this object gets assigned with all customer objects.
Upvotes: 1
Views: 181
Reputation: 39014
There is a clear error:
$http.put("/api/customers/{id}" + customer.id, customer)
This will try to PUT to an url like this:
http://yoursite/api/customers/{id}927
You need to remove the {id}
part, so that your url is correct:
http://yoursite/api/customers/927
The segment enclosed in braces only exists in the server side route template, and it's used to extract the parameter from the incoming URI.
Upvotes: 2